views:

179

answers:

1

Hello,

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 even 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?

+1  A: 

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.

CMS
@Alex, since you already have the DOM element you want to *click*, we can use the `Node.ownerDocument` property instead of using `content.document`, try it out ;-)
CMS