I want to use JavaScript with WebDriver (Selenium 2) using Java.
I've followed some a guide and on Getting Started page: there is an instruction at 1st line to run as:
$ ./go webdriverjs
My question: From which folder/location the command mentioned above will be run/executed?
JavaScriptExecutor is used when Selenium Webdriver fails to click on any element due to some issue. JavaScriptExecutor provides two methods “executescript” & “executeAsyncScript” to handle. Executed the JavaScript using Selenium Webdriver.
Yes, Java is bit faster - but speed of execution is irrelevant for a beginner, or for automating Selenium. Javascript is a must for web front end developer - but Javascript is more quirky, confusing and less forgiving than Python.
Based on your previous questions, I suppose you want to run JavaScript snippets from Java's WebDriver
. Please correct me if I'm wrong.
The WebDriverJs
is actually "just" another WebDriver
language binding (you can write your tests in Java, C#, Ruby, Python, JS and possibly even more languages as of now). This one, particularly, is JavaScript, and allows you therefore to write tests in JavaScript.
If you want to run JavaScript code in Java WebDriver
, do this instead:
WebDriver driver = new AnyDriverYouWant(); if (driver instanceof JavascriptExecutor) { ((JavascriptExecutor)driver).executeScript("yourScript();"); } else { throw new IllegalStateException("This driver does not support JavaScript!"); }
I like to do this, also:
WebDriver driver = new AnyDriverYouWant(); JavascriptExecutor js; if (driver instanceof JavascriptExecutor) { js = (JavascriptExecutor)driver; } // else throw... // later on... js.executeScript("return document.getElementById('someId');");
You can find more documentation on this here, in the documenation, or, preferably, in the JavaDocs of JavascriptExecutor
.
The executeScript()
takes function calls and raw JS, too. You can return
a value from it and you can pass lots of complicated arguments to it, some random examples:
1.
// returns the right WebElement // it's the same as driver.findElement(By.id("someId")) js.executeScript("return document.getElementById('someId');");
// draws a border around WebElement WebElement element = driver.findElement(By.anything("tada")); js.executeScript("arguments[0].style.border='3px solid red'", element);
// changes all input elements on the page to radio buttons js.executeScript( "var inputs = document.getElementsByTagName('input');" + "for(var i = 0; i < inputs.length; i++) { " + " inputs[i].type = 'radio';" + "}" );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With