Calling C# BHO methods from Javascript

前端 未结 2 1277
陌清茗
陌清茗 2020-12-08 17:06

I\'m trying to figure out how to call C# methods in my BHO object from Javascript within the page. I found numerous pages on how to do it in C++/ATL/Com such as:

Bro

相关标签:
2条回答
  • 2020-12-08 17:46

    I hate to answer my own question, but I really feel like the community ought to know the answer because it is short, simple, and beautiful with C# 4.0 and SO many people seem to have this problem.

    Make sure that you correctly expose the Browser Helper Object:

    [ComVisible(true),
     Guid("DA8EA345-02AE-434E-82E9-448E3DB7629E"),
     ClassInterface(ClassInterfaceType.None), ProgId("MyExtension"),
     ComDefaultInterface(typeof(IExtension))]
    public class BrowserHelperObject : IObjectWithSite, IExtension
    {
        ...
        public int Foo(string s) { ... }
        ...
        public void OnDocumentComplete(dynamic frame, ref dynamic url)
        {
            ...
            dynamic window = browser.Document.parentWindow;
            IExpando windowEx = (IExpando)window;
            windowEx.AddProperty("myExtension");
            window.myExtension = this;
            ...
        }
        ...
    }
    

    And you will need a definition for your extensions:

    [ComVisible(true),
     Guid("4C1D2E51-018B-4A7C-8A07-618452573E42"),
     InterfaceType(ComInterfaceType.InterfaceIsDual)]
    public interface IExtension
    {
        [DispId(1)]
        int Foo(string s);
        ...
    }
    

    You can access your Browser Helper Object in javascript thus:

    var result = window.myExtension.Foo("bar");
    

    or just

    var result = myExtension.Foo("bar");
    

    That's it. Stop banging your head against the wall and go celebrate!

    0 讨论(0)
  • 2020-12-08 17:48

    Also, after you add property you need to make sure to release COM references of window and windowEx

    0 讨论(0)
提交回复
热议问题