I am testing a web app using WebDriver/Selenium-2.0a4 with IE8. My
goal is to simulate a right-click in JavaScript since WebDriver
doesn't allow it yet. As a way to get there, I am trying to simulate a
left-click. I am using Eclipse IDE. Posts recommend creating an event
and firing it with element.fireEvent; however I could not get that to
work. It does not throw an error, but nothing else happens. Does this
call work in WebDriver/Selenium-2.0a4 with IE8?
To give an example using JavaScript element.click() -- this DOES work
to do a left-mouse click:
StringBuffer javaScript = new StringBuffer();
javaScript.append(" var
element=document.getElementsByTagName('a');");
javaScript.append(" for (var i = 0; i < element.length; i++){ ");
javaScript.append(" if
(element[i].innerHTML.indexOf('approveRecordingDiv+')!=-1) {myElement=
element[i]; } ");
javaScript.append(" }");
javaScript.append(" myElement.click();");
((JavascriptExecutor) driver).executeScript(javaScript.toString());
Thread.sleep(3000);
But this does NOT work for me to left-click. Any suggestions?
// Same code as above, but, this is instead of myElement.click();
javaScript.append(" var fired = myElement.fireEvent('onclick');");
((JavascriptExecutor) driver).executeScript(javaScript.toString());
Thread.sleep(3000);
For right-click, I have tried several approaches which involve
creating an event and using init to populate the values. The init
statement causes an error.
I also read that for right click, you have to call use the parent
document, rather than the element itself for the event.
Neither approach has worked though.
javaScript.append(" var evt =
elmnt.ownerDocument.createEventObject();");
-- I have also tried with passing MouseEvents and MouseEvent
javaScript.append(" var evt =
elmnt.ownerDocument.createEventObject('MouseEvents');");
javaScript.append("evt.initMouseEvent('click', true, true,");
javaScript.append(" elmnt.ownerDocument.defaultView, 1, 0, 0, 0, 0,
false, false, false, false, 2, null);");
javaScript.append(" elmnt.fireEvent('onclick',evt); ");
The posts on line also do not seem to be using the JavascriptExecutor
object, but maybe they just removed those references to make the code
easier to read?
When I use the init, this is the error returned in Eclipse:
Failed to execute: Exception occurred:
System info:
os.name: 'Windows XP', os.arch: 'x86', os.version: '5.1',
java.version: '1.6.0_20'
Driver info: driver.version: ie
(function() { return function(){ var
element=document.getElementsByTagName('a'); for (var i = 0; i <
element.length; i++){
if (element[i].innerHTML.indexOf('approveRecordingDiv+')!=-1)
{myElement= element[i]; } } var evt =
myElement.ownerDocument.createEventObject('MouseEvents');evt.initMouseEvent('click',
true, true);};})();