ActiveX custom event cannot work on IE11

yushulx picture yushulx · Jul 16, 2013 · Viewed 12.7k times · Source

I upgraded my IE from version 10 to 11 and found that my ActiveX custom event couldn't work.

The reason is that IE11 does not support attachEvent any more, and seems I have to use addEventListener. For example previously I used

obj.attachEvent("onSelected", method1); 

and now, it is

obj.addEventListener("onSelected",method1,false); 

After changing the code, the method1 cannot be triggered. I have no idea how to bind custom event, which is implemented in ActiveX plugin, to JS method and make it work on IE11?

Answer

kayahr picture kayahr · Nov 13, 2013

The only way I found so far for IE 11 is using the for...event script blocks:

<script for="myActiveX" event="onSelected(param1, param2)">
  method1(param1, param2);
</script>
<object id="myActiveX" ...></object>

Both elements can also be created dynamically with JavaScript. You only must make sure you set the for attribute with the setAttributemethod:

var handler = document.createElement("script");
handler.setAttribute("for", "myActiveX");
handler.event = "onSelected(param1, param2)";       
handler.appendChild(document.createTextNode("method1(param1, param2);"));
document.body.appendChild(handler);

var activeX = document.createElement("object");
activeX.id = "myActiveX"; 
activeX.codebase = "foobar.cab";
activeX.classid = "CLSID:123456789-1234-1234-1234-123456789012";
document.body.appendChild(activeX);

Older IE versions (IE 8 and older) don't like the above code. For these older browsers you must pass the codebase parameter and for parameter with the createElement method:

var handler = document.createElement('<script for="myActiveX">');
...
var activeX = document.createElement('<object classid="CLSID:123456789-1234-1234-1234-123456789012">');

Newer browsers will throw an exception when encountering this code so to support all IE versions you must catch this exception and then use the other method.