Il n'y a aucun moyen direct .NET pour définir un élément de script dans la tête de document. Pour contourner ce problème, vous pouvez référencer mshtml.dll et utiliser l'interface IHTMLDocument2. En outre, vous pouvez également utiliser une classe wrapper pour exposer les fonctionnalités dont vous avez besoin. (c'est-à-dire les propriétés Text ou src de l'élément de script afin que vous puissiez définir votre code de script). Ensuite, vous avez juste besoin d'une méthode qui implémente l'interface wrapper personnalisée. Quelque chose comme indiqué ci-dessous ...
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
/// <summary>
/// A COM interface is needed because .NET does not provide a way
/// to set the properties of a HTML script element.
/// This class negates the need to refrence mshtml in its entirety
/// </summary>
[ComImport, Guid("3050F536-98B5-11CF-BB82-00AA00BDCE0B"),
InterfaceType((short)2),
TypeLibType((short)0x4112)]
public interface IHTMLScriptElement
{
/// <summary>
/// Sets the text property
/// </summary>
[DispId(1006)]
string Text
{
[param: MarshalAs(UnmanagedType.BStr)]
[PreserveSig,
MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime),
DispId(-2147417085)]
set;
}
/// <summary>
/// Sets the src property
/// </summary>
[DispId(1001)]
string Src
{
[param: MarshalAs(UnmanagedType.BStr)]
[PreserveSig,
MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime),
DispId(-1001)]
set;
}
}
// Inject script element
public static void InjectJavascript(string javascript, HTMLDocument doc)
{
if (doc != null)
{
try
{
// find the opening head tag
HtmlElement head = doc.GetElementsByTagName("head")[0];
// create the script element
HtmlElement script = doc.CreateElement("script");
// set it to javascirpt
script.SetAttribute("type", "text/javascript");
// cast the element to our custom interface
IHTMLScriptElement element = (IHTMLScriptElement)script.DomElement;
// add the script code to the element
element.Text = "/* <![CDATA[ */ " + javascript + " /* ]]> */";
// add the element to the document
head.AppendChild(script);
}
catch (Exception e)
{
MessageBox.show(e.message);
}
}
}
Vous utiliseriez comme ça, où myDoc est votre document html ...
InjectJavascript("function foo(bar) { alert(bar); }", myDoc); // inject the 'foo' function
et le tester comme ça ...
myDoc.InvokeScript("foo", new object[] { "Hello!" }); // alerts 'hello!'
savez-vous des restrictions de sécurité? –