2009-03-07 17 views

答えて

1

.NETで直接ドキュメントヘッドにスクリプト要素を設定する方法はありません。この問題を回避するには、mshtml.dllを参照してIHTMLDocument2インターフェイスを使用します。また、必要な機能を公開するためにラッパークラスを使用することもできます。 (つまり、スクリプトコードを設定できるように、スクリプト要素のTextまたはsrcプロパティ)。次に、カスタムラッパーインターフェースを実装するメソッドが必要です。何かMYDOCは、HTMLドキュメントここであなたは、このようにそれを使用することになり...以下

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); 
     } 
    } 
} 

を示す...

InjectJavascript("function foo(bar) { alert(bar); }", myDoc); // inject the 'foo' function 

とこのようにそれをテスト...

myDoc.InvokeScript("foo", new object[] { "Hello!" }); // alerts 'hello!' 
+0

あなたはどのようなセキュリティrestricationsの知っていますか? –

0

HTMLWindowクラスを取得するにはHTMLDocument :: Windowプロパティを使用し、ネイティブIEインターフェイスを取得するにはHTMLWindow :: DomWindowプロパティを使用します。その後、IHTMLWindow2 :: execScriptを呼び出します。

http://msdn.microsoft.com/en-us/library/aa741364(VS.85).aspx

+0

HTMLDocumentClassにウィンドウプロパティがありません... –

+0

と私は実際にハード私は無効なキャスト例外を取得しようとする –

0

HTMLDocumentのはWindow性質を持っています。

また、HtmlDocumentのCreateElementメソッドを使用して、スクリプトを現在のドキュメントに挿入することもできます。

関連する問題