Sameera De Silva
4 min readOct 30, 2019

Webdriver JavascriptExecutor interact with elements and open and handle multiple tabs and get url and domain

This is a continuation of https://medium.com/@smeesheady/using-webddriver-javascriptexecutor-navigate-to-a-url-and-navigate-forward-and-backward-and-7c0e46ff5ee4

Please see the full code .

package com.webdriver.blogs;import java.io.IOException;import java.util.ArrayList;import java.util.concurrent.TimeUnit;import org.openqa.selenium.By;import org.openqa.selenium.JavascriptExecutor;import org.openqa.selenium.WebDriver;import org.openqa.selenium.chrome.ChromeDriver;import org.openqa.selenium.chrome.ChromeOptions;import org.testng.Assert;import org.testng.annotations.AfterSuite;import org.testng.annotations.BeforeClass;import org.testng.annotations.Test;/*It's a Selenium Interface which directly lets you Interact with HTML DOM of the web page.It  is being implemented by all the following classes:FirefoxDriverChromeDriverInternetExplorerDriverEdgeDriverOperaDriverSafariDriverRemoteWebDriverEventFiringWebDriverit does so by executing JavaScript expressions using Following Syntax :executeScript(): This method executes JavaScript in the context of the currently selected frame or window.The script fragment provided will be executed as the body of an anonymous function.Within the script you need to use document to refer to the current document.Note that local variables will not be available once the script has finished executing, though global variables will persist.*JavascriptExecutor provides a way to automate a user interaction even when page is not essentially loaded completely or elements are placed in a way that the direct interaction is blocked.While you execute your Selenium script at times because of cross domain policies browsers enforce your script execution may fail unexpectedlyThis however is also the disadvantage too, if you want to automate a web page as if a real user experience.That said, although it is a really powerful option,but we should try not to use JavaScript Executor unless there is no standard way of doing it via Selenium.*/public class JavaScriptSamplesInWebdriver {WebDriver driver;@BeforeClass()public void setUp() {System.setProperty("webdriver.chrome.driver",System.getProperty("user.dir")+"\\Jar_files\\chromedriver.exe");ChromeOptions options = new ChromeOptions();options.addArguments("start-maximized");driver = new ChromeDriver(options);driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);driver.manage().window().maximize();}@Test(priority=1,enabled=false,description="Navigate to website using java script and go back and forward")public void GoToUrlAndNavigateBackAndForward() throws InterruptedException {String url="https://bitbucket.org/";//Define a js object with type of JavascriptExecutor class and here the TypeCasting is appliedJavascriptExecutor js = (JavascriptExecutor) driver;//The url is parameterized and \ \ signs are optional and This is similar to  driver.get("https://www.bbc.com/");js.executeScript("window.location = \'"+url+"\'");//Without parameterizing the urljs.executeScript("window.location = 'https://www.bbc.com/'");//To navigate back (-1)--> back   This is similar to  driver.navigate().back();js.executeScript("window.history.go(-1)");Thread.sleep(6000);//To go forward Forward(-1)--> front.     driver.navigate().forward();js.executeScript("window.history.forward(-1)");Thread.sleep(6000);//Refresh the page  This is similar to driver.navigate().refresh();js.executeScript("history.go(0);");}@Test(priority=2,enabled=false,description="Navigate to website and verify details using a Javascript")public void navigateToWebSite() {//Creating the JavascriptExecutor interface object called js by Type castingJavascriptExecutor js = (JavascriptExecutor) driver;//make sure to put '' so the value is 'https://www.google.com/'String url="https://www.google.com/";//js.executeScript("window.location = 'https://www.google.com/'");js.executeScript("window.location = \'"+url+"\'");String actualWebTitle =  js.executeScript("return document.title;").toString();//driver.getTitle(); <title>Google</title>System.out.println("Actual Title of the website is "+actualWebTitle);Assert.assertEquals("Google", actualWebTitle,"Web site's title mismatches");//Fetching the Domain Name of the site. Tostring() change object to name.String domainName = js.executeScript("return document.domain;").toString();Assert.assertEquals("www.google.com", domainName,"Web site's domain mismatches");System.out.println("Domain name of the site = "+domainName);//get  the URL of the site.String currentUrl = js.executeScript("return document.URL;").toString();String webDrivercurrentUrl=driver.getCurrentUrl();System.out.println("webDrivercurrentUrl is "+webDrivercurrentUrl);Assert.assertEquals("https://www.google.com/", currentUrl,"Web site's url mismatches");System.out.println("URL of the site = "+currentUrl);String pageIsReady=js.executeScript("return document.readyState").toString();System.out.println("Page is ready "+pageIsReady);Assert.assertEquals("complete", pageIsReady,"Web site is loaded and page is ready");}@Test(priority=3,enabled=false,description="Ener some values using javascript")public void FillValuesUsingJavaScript() throws InterruptedException {String url="https://stackoverflow.com/users/signup?ssrc=head&returnurl=%2fusers%2fstory%2fcurrent";JavascriptExecutor js = (JavascriptExecutor) driver;js.executeScript("window.location = \'"+url+"\'");//Enter a value using javascript by locating element using  getElementByIdjs.executeScript("document.getElementById('display-name').value='Sam';");//Enter a value using javascript by locating element usingjs.executeScript("document.getElementById('password').value='welcome123';");//We can parameterize the locator and valueString emailval="para@yahoo.com";String emailLocatorByName="email";String passwordLocatorByName="password";js.executeScript("document.getElementById('"+emailLocatorByName+"').value=\'"+emailval+"\';");//Click on text field by locating element busing  getElementById//js.executeScript("document.getElementById('password').click();");js.executeScript("document.getElementById('"+passwordLocatorByName+"').click();");//Handle checkboxjs.executeScript("document.getElementById('opt-in').checked=true;");Thread.sleep(12500);js.executeScript("document.getElementById('opt-in').checked=false;");String theTextIWant = (String) js.executeScript("return arguments[0].value;",driver.findElement(By.xpath("//input[@id='display-name']")));System.out.println("========================="+theTextIWant);//Refresh the page  This is similar to driver.navigate().refresh();js.executeScript("history.go(0);");//Javascript command//http://www.inviul.com/send-texts-get-texts-selenium///https://www.guru99.com/execute-javascript-selenium-webdriver.html}@Test(priority=4,enabled=true,description="Click buttons using java Script")public void ClickButtonUsingJavaScript() throws InterruptedException {String url="https://www.ebay.com/";JavascriptExecutor js = (JavascriptExecutor) driver;js.executeScript("window.location = \'"+url+"\'");String txtSearchLocator="gh-ac";String btnSearchLocatouter="gh-btn";String searchValue="Router";js.executeScript("document.getElementById('"+txtSearchLocator+"').value=\'"+searchValue+"\';");js.executeScript("document.getElementById('"+btnSearchLocatouter+"').click();");//Open an another tab without parameterising the url// js.executeScript("window.open('https://www.facebook.com')");//Open an another tab by parameterising the urlString secondurl="https://www.facebook.com";js.executeScript("window.open(\'"+secondurl+"\')");// Store all currently open tabs in tabsArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());// Switch newly open Tab by index 1driver.switchTo().window(tabs.get(1));String txtEmail="email";String txtEmailhLocatouterVal="sam@fb.com";String txtPassword="pass";String txtPasswordVal="welcome123";js.executeScript("document.getElementById('"+txtEmail+"').value=\'"+txtEmailhLocatouterVal+"\';");js.executeScript("document.getElementById('"+txtPassword+"').value=\'"+txtPasswordVal+"\';");Thread.sleep(7500);// Close newly open tab after performing above operations. This is similar to driver.close();js.executeScript("window.close()");// Switch to old(Parent) tab.driver.switchTo().window(tabs.get(0));//Clear text field in main windowjs.executeScript("document.getElementById('"+txtSearchLocator+"').value='';");Thread.sleep(7500);}@AfterSuite()public void shutDown() {JavascriptExecutor js = (JavascriptExecutor) driver;js.executeScript("window.close()"); // didnt workdriver.close(); //This method closes the browser window on which the focus is set.driver.quit();// basically calls driver.dispose a now internal method which in turn closes all of the browser windows and ends the WebDriver session gracefully.try {Runtime.getRuntime().exec("taskkill /F /IM chromedriver.exe");} catch (IOException e1) {e1.printStackTrace();}System.out.println("***************End of testing shutdown happend**************************");}}

Please see the free Video URL — https://youtu.be/H1INiSQlnhM

Please follow the Author — https://www.linkedin.com/in/sameera-de-silva-11247922/

Responses (1)