BHO开发,在js中调用c#接口

BHO开发中, javascript中调用c#中方法

1.首先定义一个c#的接口给js调用

    [
        ComVisible(true),
        Guid("FC4801A3-2BA9-11CF-A229-00AA003D7352"), // Never EVER change this UUID!! It allows this BHO to find IE and attach to it
        InterfaceType(ComInterfaceType.InterfaceIsDual)
    ]
    public interface IExtension
    {
        [DispId(1)]
        bool Foo();  //声明
    }

2.然后在BHO主类中声明

namespace IEExtension
{
    [
        ComVisible(true),
        Guid("2159CB25-EF9A-54C1-B43C-E30D1A4A8277"),
        ClassInterface(ClassInterfaceType.None), ProgId("MyExtension"),  //ProgId要加
        ComDefaultInterface(typeof(IExtension))    //这行也要加上
    ]
    public partial class BHO : IObjectWithSite , IExtension   //继承要导出的类
    {
        public InternetExplorer ieInstance;//IE TAB is just an IE instance
        public IHTMLDocument3 document;
        public HTMLElementEvents2_Event rootElementEvents = null;
        public IHTMLEventObj2 eventObj;
        ....
        bool Foo() //实现该方法
        {
            return true;
        }

3.在BeforeScritpt方法中,添加如下代码

setSite中

_webBrowser = (IWebBrowser)site;
 ieInstance.BeforeScriptExecute += 
                    new DWebBrowserEvents2_BeforeScriptExecuteEventHandler(
                        ieInstance_BeforeScritpt);
 public void ieInstance_BeforeScritpt(object pDispWindow)
        {
            dynamic window = _webBrowser.Document.parentWindow;
            var windowEx = (IExpando)window;
            PropertyInfo p = windowEx.AddProperty("myExtension");
            p.SetValue(windowEx, this);
        }

4.在js中调用

 var checkResult = window.myExtension.Foo();

参考连接:
https://ask.helplib.com/CSharp/post_12525833
https://stackoverflow.com/questions/9287961/calling-c-sharp-bho-methods-from-javascript

猜你喜欢

转载自blog.csdn.net/weixin_34044273/article/details/86994946