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

3.3k views Asked by At

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 Studio displays the parameter type as just object.

I looked for an IEventListener interface or something similar but didn't find one. What am I supposed to pass in?

1

There are 1 answers

0
ide On BEST ANSWER

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.