Alex Rivera | Logout

JavaScript simulate right click through code

Asked 2009-01-11T22:53:28.520
32

I am writing some UI tests using Selenium and i have a JavaScript Tree control, using the Dojo toolkit.

I have implemented a context menu for each node of the tree using the examples that Dojo provide, but I need the Selenium test to "invoke" the right click on the tree node, but I cannot get this to work. The tests simply do not simulate the right-click event through JavaScript, and the context menu does not show up.

Has anyone had any experience in invoking the right click on a context menu using Dojo and Selenium? Or have any ideas as to how to do it?

Edit
Report

2 Answers

12

Just for good measure, here is a bit of doco on the parameters:

var myEvt = document.createEvent('MouseEvents');
myEvt.initMouseEvent(
   'click'          // event type
   ,true           // can bubble?
   ,true           // cancelable?
   ,window      // the event's abstract view (should always be window)
   ,1              // mouse click count (or event "detail")
   ,100           // event's screen x coordinate
   ,200           // event's screen y coordinate
   ,100           // event's client x coordinate
   ,200           // event's client y coordinate
   ,false         // whether or not CTRL was pressed during event
   ,false         // whether or not ALT was pressed during event
   ,false         // whether or not SHIFT was pressed during event
   ,false         // whether or not the meta key was pressed during event
   ,1             // indicates which button (if any) caused the mouse event (1 = primary button)
   ,null          // relatedTarget (only applicable for mouseover/mouseout events)
); 
answered 2009-01-12T01:26:09.087
4

Here is a more correct version if you do not care about where the context menu gets fired up

function fireContextMenu(el) {
  var evt = el.ownerDocument.createEvent("HTMLEvents")
  evt.initEvent('contextmenu', true, true) // bubbles = true, cancelable = true

  if (document.createEventObject) {
    return el.fireEvent('oncontextmenu', evt)
  }
  else {
    return !el.dispatchEvent(evt)
  }
}

If you do, we may have to use the previous one, fix up it's behaviour in IE, and populate the screenX, screenY, clientX, clientY etc appropriately

answered 2009-01-12T01:16:27.903

Your Answer