AndroidApacheAutomation FrameworkJava, JavaScriptTechnical blogTrending

How to execute javascript in webdriver using javaScriptExecutor using executescript method

JavaScriptExecutor can be used to execute javascript in WebDriver. JavaScriptExecutor actions like the way Xpath, Link, CSS, Id locators works in Selenium Webdriver.

javaScriptExecutor is supported by Selenium library and for that you need to import ‘org.openqa.selenium.JavascriptExecutor ‘ in your program.

In Selenium, javaScriptExecutor works like an interface and facilitates Javascript execution in there.

JavaScriptExecutor has two methods.one of the method is as below,

1) executescript – This method will block the execution of next line of code unitl it is completed.

example:

JavascriptExecutor js = (JavascriptExecutor) driver;  

js.executeScript(Script,Arguments);

 

Example for executeScript

import org.openqa.selenium.JavascriptExecutor;    

import org.openqa.selenium.By;   

import org.openqa.selenium.WebDriver;   

import org.openqa.selenium.WebElement;   

import org.openqa.selenium.firefox.FirefoxDriver;   

import org.testng.annotations.Test;   

  

public class ExecuteScriptExample {   

@Test   

public void ExecuteScriptTest()

  

{   

    WebDriver driver= new FirefoxDriver();   

    JavascriptExecutor js = (JavascriptExecutor)driver;   

    driver.get(“your website url having login option”);   

    WebElement button =driver.findElement(By.name(“xxxxxxxx”));   

    driver.findElement(By.name(“uid”)).sendKeys(“admin”);   

    driver.findElement(By.name(“password”)).sendKeys(“admin”);   

    js.executeScript(“arguments[0].click();”, button);

    js.executeScript(“alert(‘Test is completed – welcome to home page’);”);   

  

}   

}

One thought on “How to execute javascript in webdriver using javaScriptExecutor using executescript method

Comments are closed.