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

时间:2019-07-03 09:44:49

标签: internet-explorer bho

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

1 个答案:

答案 0 :(得分:1)

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

(1)将引用和导入添加到以下组件:

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

(2)在BHO类声明上方定义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类实现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)注册要由Internet Explorer加载的BHO

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

有关更多详细信息和说明,请参阅下面的链接。

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