Reputation: 1910
I'm trying to create a custom Event in JavaScript.
I have a WPF applciation with a WebBrowser that run Internet Explorer 9.
The code :
var evt = document.createEvent("Event");
evt.initEvent("readerstatechanged", true, false);
window.dispatchEvent(evt);
Error :
I also tried :
var evt = new Event("Event");
Error :
Do you have an idea how to create a custom event with IE 9 ?
Edit :
I changed with createEventObject, but then the "InitEvent" doesn't work :
var evt = document.createEventObject("Event");
evt.initEvent("printerstatechanged", true, false);
window.dispatchEvent(evt);
Then I need to use attachEvent like this :
window.attachEvent('printerstatechanged', function (e) {
//Do something
});
Upvotes: 2
Views: 4225
Reputation: 1074218
IE9 supports DOM3 events, so you can create and hook custom events. Here's a complete example, which works in IE9 and any other DOM3-compatible browser: Live Copy
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>IE9+ Custom Event</title>
</head>
<body>
<script>
(function() {
// Hooking the event, in this case on documentElement
document.documentElement.addEventListener("readerstatechanged", function() {
display("readerstatechanged received");
});
// Creating it
display("Creating");
var evt = document.createEvent("CustomEvent");
evt.initCustomEvent("readerstatechanged", true, false, {});
// Could put custom data here -------------------------^^
// Firing it on documentElement
display("Firing");
document.documentElement.dispatchEvent(evt);
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
})();
</script>
</body>
</html>
It will not work in IE8, but as you've emphasized IE9...
If your site is being displayed in the seriously-misnamed "compatibility view," IE turns off these standard features, making it less compatible with the real world rather than more. Using "compatibility view" for intranet sites is the default setting, I believe, which is just asinine. You can reassure IE that you actually know what you're doing by adding a meta
tag to your head
section:
<meta http-equiv="X-UA-Compatible" content="IE=Edge"/>
Upvotes: 4