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.initEvent("click", true, false );
toClick[0].dispatchEvent(evt);
This is not working for me, and I was wondering if this is e开发者_开发问答ven possible? (to trigger events from a Firefox extension)?
I think it may have something to do with what document I create the event on...but I'm not sure.
If so, how does one do it?
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)) {
throw new Error("Only MouseEvents supported");
}
if (typeof userOptions != 'undefined'){ // set the userOptions
for (var prop in userOptions) {
if (userOptions.hasOwnProperty(prop))
options[prop] = userOptions[prop];
}
}
// initialize the event object
event.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.
精彩评论