Navigate to url, enter Text or click on webelement with Javascript using JavascriptExecutor Interface in selenium and understanding its arguments




JavaScriptExecutor is an Interface implemented by RemoteWebDriver class that helps to execute JavaScript through Selenium Webdriver. It has two methods which help in executing javascript on a webpage.
We will use its executeScript() method to execute javascript.
1) Object executeScript(String javascript, Object... args) - It takes first parameter as the JavaScript to execute, and second parameter is any arguments to the script and may be empty. This method returns Object which may be Boolean, Long, Double, String, List, Map or WebElement or null.
Lets explain how we can execute javascript on a webpage with this method.
Snippet-1  This uses javascipt to navigate to an URL
WebDriver driver = new FirefoxDriver();
JavascriptExecutor executor =(JavascriptExecutor)driver;
executor.executeScript("window.location.href = 'https://app.box.com';");  
 
Snippet-2  Click on a web element using javascript only having element id "login-email"
executor.executeScript("document.getElementById(\"login-email\").click();");
 
Snippet-3 Click on a webelement using javascript and sending first argument as WebElement
WebElement emailTextField = driver.findElement(By.id("login-email"));
executor.executeScript("arguments[0].click();",emailTextField);  
 
Snippet-4 Sending text to webelement using javascript and sending first argument as WebElement and second argument as String
executor.executeScript("arguments[0].value=arguments[1]",emailTextField,"qacult");

**************************************************************************************

QACult Best Software Testing Courses in Chandigarh tricity.- We love to enhance your knowledge.

QACult is the premier institute catering to the requirements of experienced and fresh pass-out that gives leaders like you a new way to experience Quality engineering—while you work and giving you the flexibility to both advance your career.
Our faculty have 12+ years of industrial experience and have developed many automation testing frameworks in java using TestNG or BDD (cucumber) methodology. We expertise in developing automation testing frameworks in java, python, javascript, php, ruby(WATIR-webdriver & Capybara) and Appium.
please subscribe our channel for more such updates:  
And visit our website: www.qacult.com for various blogs and Upcoming Events.

Comments

Popular posts from this blog

Robot Framework With Python: An Open Source Framework For RPA

Robot Framework in python with RIDE

How to do copy Paste in browser using selenium using Actions class