How do I add an event listener using MSHTML's addEventListener in IE9?

前端 未结 1 918
有刺的猬
有刺的猬 2021-01-05 13:45

The MSDN documentation for addEventListener says it accepts a callback function in the form of an IDispatch * object. From C# (I\'m using COM interop), Visual S

相关标签:
1条回答
  • 2021-01-05 13:57

    After some research, I learned that these COM connection points (event handlers) are specified with DispId(0). Callback functions are represented by instances of classes like:

    // These attributes may be optional, depending on the project configuration.
    [ComVisible(true)]
    [ClassInterface(ClassInterfaceType.AutoDispatch)]
    public class EventListener
    {
        [DispId(0)]
        // The "target" parameter is an implementation detail.
        public void NameDoesNotMatter(object target, IDOMEvent evt) { ... }
    }
    

    Since DispId(0) specifies the default method to invoke, the actual name of the method doesn't matter. However, the method parameters certainly do matter. For example, IHTMLElement.onclick must be assigned a callback with no arguments, while IHTMLElement2.attachEvent takes a callback with one parameter of type IHTMLEventObj (or IHTMLEventObj2, ..., 6 , or even just object).

    In summary, COM IDispatch callbacks can be implemented in C# using a COM-visible class with a method that accepts the correct arguments and is annotated with [DispId(0)].


    Despite all of this, solutions that avoid the W3C DOM Events API may be more appropriate, as IE9 DOM objects do not support this method when the browser is using a lower document mode for compatibility. For example, an extension that uses addEventListener will fail on a page like Bing, which is rendered in IE7 mode.

    It also doesn't seem possible to set the document mode used by an IWebBrowser2 instance aside from manually doing it through the F12 developer tools.

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