Workaround For Firefox's Lack Of Window.event?
I have been caught off guard by Firefox's lack of window.event ... namely
Solution 1:
Here's an ugly hack, based on the assumption that all event listeners will ultimately be registered by the EventTarget.addEventListener()
method. The "solution" below changes EventTarget
's prototype (yuck!) so as to wrap all event listeners in a method that will assign the event to window.event
before delegating to the actual listener.
const addEventListener = EventTarget.prototype.addEventListener;
EventTarget.prototype.addEventListener = function(name, handler) {
addEventListener.call(this, name, function(event) {
window.event = event;
handler(event);
})
};
function clicked() {
// just demonstrating that window.event is set
console.log(window.event.target.innerHTML);
}
document.getElementById('one').addEventListener('click', clicked);
document.getElementById('two').addEventListener('click', clicked);
<button id="one">Test 1</button>
<button id="two">Test 2</button>
The above just illustrates a possible approach and is largely untested. Your mileage may vary.
Update
As pointed out in the comments, this will not work for event handlers bound through the on...
HTML attributes or assigned using the Element.on...
properties.
An alternative (and arguably safer) approach could be to use event capturing on the document element, and perform the assignment to window.event
there.
document.documentElement.addEventListener('click', function(event) {
window.event = event;
}, true);
function clicked() {
// just demonstrating that window.event is set
console.log(window.event.target.innerHTML);
}
document.getElementById('one').addEventListener('click', clicked);
document.getElementById('two').onclick = clicked;
<button id="one">Test 1</button>
<button id="two">Test 2</button>
<button id="three" onclick="clicked()">Test 3</button>
Post a Comment for "Workaround For Firefox's Lack Of Window.event?"