How to run java script on webdriver

Steps,

  1. create a java project using Eclipse IDE
  2. add a package and then a class (refer below code for package name and class name)
  3. then add necessary jar files (selenium-server-standalone-2.53.0, testing, etc)
  4. then copy/paste and update the code in your IDE
  5. place chromedriver in the folder and update code below for folder “Users/shali/Downloads/” path matching your pc folder
  6. run your script to verify results.

JavaScriptExample;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.remote.DesiredCapabilities;
public class JavaScriptTest {
public static void main(String[] args) {
 System.setProperty(“webdriver.chrome.driver”, “/Users/shali/Downloads/chromedriver”);
 ChromeOptions options = new ChromeOptions();
options.addArguments(“window-size=1024,680”);
 DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
WebDriver driver = new ChromeDriver(capabilities);
 driver.get(“https://shalimatech.com/”);
 if (driver instanceof JavascriptExecutor) {
((JavascriptExecutor) driver)
.executeScript(“alert(‘testing for java script’);”);
}
  }
}