IE - C#,如何将 JavaScript 文件注入网页?

IE - C#, How to inject a JavaScript file to a web page?

我正在从事 IE 扩展开发。我想在浏览器(IE)打开时注入一个外部JS文件。

请参考此代码示例可能有助于解决您的问题。

(1) 添加对以下组件的引用和导入:

using SHDocVw;
using mshtml;
using System.IO;
using Microsoft.Win32;
using System.Runtime.InteropServices; 

(2) 在 BHO class 声明之上定义 IOleObjectWithSite 接口,如下所示:

[
    ComVisible(true),
    InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
    Guid("FC4801A3-2BA9-11CF-A229-00AA003D7352")
]
public interface IObjectWithSite
{
    [PreserveSig]
    int SetSite([MarshalAs(UnmanagedType.IUnknown)]object site);
    [PreserveSig]
    int GetSite(ref Guid guid, out IntPtr ppvSite);
}

(3) 使 BHO class 实现 IOleObjectWithSite 接口

[
        ComVisible(true),
        Guid("2159CB25-EF9A-54C1-B43C-E30D1A4A8277"),
        ClassInterface(ClassInterfaceType.None)
]

public class BHO : IObjectWithSite
{
  private WebBrowser webBrowser;

  public int SetSite(object site)
  {
    if (site != null)
    {
        webBrowser = (WebBrowser)site;
        webBrowser.DocumentComplete += 
          new DWebBrowserEvents2_DocumentCompleteEventHandler(
          this.OnDocumentComplete);
    }
    else
    {
        webBrowser.DocumentComplete -= 
          new DWebBrowserEvents2_DocumentCompleteEventHandler(
          this.OnDocumentComplete);
        webBrowser = null;
    }

    return 0;

  }

  public int GetSite(ref Guid guid, out IntPtr ppvSite)
  {
    IntPtr punk = Marshal.GetIUnknownForObject(webBrowser);
    int hr = Marshal.QueryInterface(punk, ref guid, out ppvSite);
    Marshal.Release(punk);
    return hr;
  }

  public void OnDocumentComplete(object pDisp, ref object URL)
  {
    HTMLDocument document = (HTMLDocument)webBrowser.Document;
  }

}

(4)实现OnDocumentComplete方法注入JavaScript代码和div元素

public void OnDocumentComplete(object pDisp, ref object URL)
{
    HTMLDocument document = (HTMLDocument)webBrowser.Document;

    IHTMLElement head = (IHTMLElement)((IHTMLElementCollection)
                           document.all.tags("head")).item(null, 0);
    IHTMLScriptElement scriptObject = 
      (IHTMLScriptElement)document.createElement("script");
    scriptObject.type = @"text/javascript";
    scriptObject.text = "\nfunction hidediv(){document.getElementById" + 
                        "('myOwnUniqueId12345').style.visibility = 'hidden';}\n\n";
    ((HTMLHeadElement)head).appendChild((IHTMLDOMNode)scriptObject);

    string div = "<div id=\"myOwnUniqueId12345\" style=\"position:" + 
                 "fixed;bottom:0px;right:0px;z-index:9999;width=300px;" + 
                 "height=150px;\"> <div style=\"position:relative;" + 
                 "float:right;font-size:9px;\"><a " + 
                 "href=\"javascript:hidediv();\">close</a></div>" +
        "My content goes here ...</div>";

    document.body.insertAdjacentHTML("afterBegin", div);
}

(5) 注册您的 BHO 以供 Internet Explorer 加载

public const string BHO_REGISTRY_KEY_NAME = 
   "Software\Microsoft\Windows\" + 
   "CurrentVersion\Explorer\Browser Helper Objects";

[ComRegisterFunction]
public static void RegisterBHO(Type type)
{
    RegistryKey registryKey = 
      Registry.LocalMachine.OpenSubKey(BHO_REGISTRY_KEY_NAME, true);

    if (registryKey == null)
        registryKey = Registry.LocalMachine.CreateSubKey(
                                BHO_REGISTRY_KEY_NAME);

    string guid = type.GUID.ToString("B");
    RegistryKey ourKey = registryKey.OpenSubKey(guid);

    if (ourKey == null)
    {
        ourKey = registryKey.CreateSubKey(guid);
    }

    ourKey.SetValue("NoExplorer", 1, RegistryValueKind.DWord);

    registryKey.Close();
    ourKey.Close();
}

[ComUnregisterFunction]
public static void UnregisterBHO(Type type)
{
    RegistryKey registryKey = 
      Registry.LocalMachine.OpenSubKey(BHO_REGISTRY_KEY_NAME, true);
    string guid = type.GUID.ToString("B");

    if (registryKey != null)
        registryKey.DeleteSubKey(guid, false);
}

更多详细信息和说明,您可以参考下面的link。

Inject HTML and JavaScript into an existing page with BHO using MS Visual Studio 2010 and C#