2011/06/06

Moving to Selenium 2 on WebDriver, Part No.5

Sending Mouse Clicks Via Javascript

Sometimes the WebDriver click does not work well,  after all it is still under development and bugs should be expected. For such case the ability to execute JavaScript through JavascriptExecutor comes in handy. Following code can send "click" or "dblclick" when used as eventName to a DOM element addressed by elementRef - JavaScript expression evaluating to a Node.


  public void fireJsEvent(String elementRef, String eventName)
    {

        String script =
        "" +
        " function eventFire(element, eventName)" +
        " {" +
        "  if (element.fireEvent)" +
        "  { element.fireEvent('on' + eventName); }" +
        "  else" +
        "  {" +
        "    var eventObject = document.createEvent('Events');" +    
        // parameters: type, bubbles, cancelable
        "    eventObject.initEvent(eventName, true, false);" +
        "    element.dispatchEvent(eventObject);" +
        "  }" +
        " };";

        String eventCall = String.format( "eventFire(%s, '%s');", elementRef, eventName );
        String exec = script + eventCall;
        js.executeScript(exec);
    }

Possible usage on a web page with dojo:

fireJsEvent("dojo.query('.someColumn:nth-child(1) li:nth-child(2)')[0]", "click");

No comments:

Post a Comment