Trigger Events From Firefox Browser Extension?
I want to trigger events from a Firefox extension, specifically click events. I've tried jQuery's .click() as well as the whole: var evt = document.createEvent('HTMLEvents'); evt
Solution 1:
First of all, for click events, you need to create an event object with type MouseEvents
, not HTMLEvents
, and use event.initMouseEvent
instead of event.initEvent
.
To access the document
of the current tab of Firefox from a XUL overlay, you can use the content.document
property, but since you already have access to the DOM element you want to click, you can use the Node.ownerDocument
property, which will refer to the top-level document
object for this node.
I have made a simple function to simulate MouseEvents:
function triggerMouseEvent(element, eventName, userOptions) {
var options = { // defaults
clientX: 0, clientY: 0, button: 0,
ctrlKey: false, altKey: false, shiftKey: false,
metaKey: false, bubbles: true, cancelable: true// create event object:
}, event = element.ownerDocument.createEvent("MouseEvents");
if (!/^(?:click|mouse(?:down|up|over|move|out))$/.test(eventName)) {
thrownew Error("Only MouseEvents supported");
}
if (typeof userOptions != 'undefined'){ // set the userOptionsfor (var prop in userOptions) {
if (userOptions.hasOwnProperty(prop))
options[prop] = userOptions[prop];
}
}
// initialize the event objectevent.initMouseEvent(eventName, options.bubbles, options.cancelable,
element.ownerDocument.defaultView, options.button,
options.clientX, options.clientY, options.clientX,
options.clientY, options.ctrlKey, options.altKey,
options.shiftKey, options.metaKey, options.button,
element);
// dispatch!
element.dispatchEvent(event);
}
Usage:
triggerMouseEvent(element, 'click');
Check a test usage here.
You can pass also an object as the third argument, if you want to change the values of the event object properties.
Post a Comment for "Trigger Events From Firefox Browser Extension?"