Executing javascript in selenium java

Executing javascript in selenium java

Indicates that a driver can execute JavaScript, providing access to the mechanism to do so. Because of cross domain policies browsers enforce your script execution may fail unexpectedly and without adequate error messaging. This is particularly pertinent when creating your own XHR request or when trying to access another frame. Most times when troubleshooting failure it’s best to view the browser’s console after executing the WebDriver request.

Method Summary

Execute an asynchronous piece of JavaScript in the context of the currently selected frame or window.

Commonly used scripts may be «pinned» to the WebDriver session, allowing them to be called efficiently by their handle rather than sending the entire script across the wire for every call.

Method Detail

executeScript

java.lang.Object executeScript​(java.lang.String script, java.lang.Object. args)
  • For an HTML element, this method returns a WebElement
  • For a decimal, a Double is returned
  • For a non-decimal number, a Long is returned
  • For a boolean, a Boolean is returned
  • For all other cases, a String is returned.
  • For an array, return a List with each object following the rules above. We support nested lists.
  • For a map, return a Map with values following the rules above.
  • Unless the value is null or there is no return value, in which null is returned
Читайте также:  For statement java syntax

executeAsyncScript

java.lang.Object executeAsyncScript​(java.lang.String script, java.lang.Object. args)
  • For an HTML element, this method returns a WebElement
  • For a number, a Long is returned
  • For a boolean, a Boolean is returned
  • For all other cases, a String is returned.
  • For an array, return a List with each object following the rules above. We support nested lists.
  • For a map, return a Map with values following the rules above.
  • Unless the value is null or there is no return value, in which null is returned
 long start = System.currentTimeMillis(); ((JavascriptExecutor) driver).executeAsyncScript( "window.setTimeout(arguments[arguments.length - 1], 500);"); System.out.println( "Elapsed time: " + (System.currentTimeMillis() - start)); 
 WebElement composeButton = driver.findElement(By.id("compose-button")); composeButton.click(); ((JavascriptExecutor) driver).executeAsyncScript( "var callback = arguments[arguments.length - 1];" + "mailClient.getComposeWindowWidget().onload(callback);"); driver.switchTo().frame("composeWidget"); driver.findElement(By.id("to")).sendKeys("bog@example.com"); 
 Object response = ((JavascriptExecutor) driver).executeAsyncScript( "var callback = arguments[arguments.length - 1];" + "var xhr = new XMLHttpRequest();" + "xhr.open('GET', '/resource/data.json', true);" + "xhr.onreadystatechange = function() " + ">;" + "xhr.send();"); JsonObject json = new JsonParser().parse((String) response); assertEquals("cheese", json.get("food").getAsString()); 

Script arguments must be a number, a boolean, a String, WebElement, or a List of any combination of the above. An exception will be thrown if the arguments do not meet these criteria. The arguments will be made available to the JavaScript via the «arguments» variable.

pin

Commonly used scripts may be «pinned» to the WebDriver session, allowing them to be called efficiently by their handle rather than sending the entire script across the wire for every call. The default implementation of this adheres to the API’s expectations but is inefficient.

unpin

Deletes the reference to a script that has previously been pinned. Subsequent calls to executeScript(ScriptKey, Object. ) will fail for the given key .

getPinnedScripts

executeScript

Calls a script by the ScriptKey returned by pin(String) . This can be thought of as inlining the pinned script and simply calling executeScript(String, Object. ) .

Читайте также:  Open pdf in browser php headers

Источник

JavaScriptExecutor in Selenium with Example

JavaScriptExecutor is an Interface that helps to execute JavaScript through Selenium Webdriver. JavaScriptExecutor provides two methods “executescript” & “executeAsyncScript” to run javascript on the selected window or current page.

Execute JavaScript based code using Selenium Webdriver

Why do we need JavaScriptExecutor?

In Selenium Webdriver, locators like XPath, CSS, etc. are used to identify and perform operations on a web page.

In case, these locators do not work you can use JavaScriptExecutor. You can use JavaScriptExecutor to perform an desired operation on a web element.

Selenium supports javaScriptExecutor. There is no need for an extra plugin or add-on. You just need to import (org.openqa.selenium.JavascriptExecutor) in the script as to use JavaScriptExecutor.

JavaScriptExecutor Methods in Selenium

executeScript

This method executes JavaScript in the context of the currently selected frame or window in Selenium. The script used in this method runs in the body of an anonymous function (a function without a name). We can also pass complicated arguments to it.

The script can return values. Data types returned are

JavascriptExecutor syntax:

JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript(Script,Arguments);
  • Script – This is the JavaScript that needs to execute.
  • Arguments – It is the arguments to the script. It’s optional.

executeAsyncScript

With Asynchronous script, your page renders more quickly. Instead of forcing users to wait for a script to download before the page renders. This function will execute an asynchronous piece of JavaScript in the context of the currently selected frame or window in Selenium. The JS so executed is single-threaded with a various callback function which runs synchronously.

How to use JavaScriptExecutor in Selenium

Here is a step-by-step process on how to use JavaScriptExecutor in Selenium:

Step 1) Import the package.

import org.openqa.selenium.JavascriptExecutor;

Step 2) Create a Reference.

JavascriptExecutor js = (JavascriptExecutor) driver;

Step 3) Call the JavascriptExecutor method.

js.executeScript(script, args);

Example of Click an Element using JavaScripExecutor in Selenium

For executeScript, we will see three different example one by one.

1) Example: Click a button to login and generate Alert window using JavaScriptExecutor.

In this scenario, we will use “Guru99” demo site to illustrate JavaScriptExecutor. In this example,

Execute JavaScript based code using Selenium Webdriver

import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.Test; public class JavaSE_Test < @Test public void Login() < WebDriver driver= new FirefoxDriver(); //Creating the JavascriptExecutor interface object by Type casting JavascriptExecutor js = (JavascriptExecutor)driver; //Launching the Site. driver.get("https://demo.guru99.com/V4/"); WebElement button =driver.findElement(By.name("btnLogin")); //Login to Guru99 driver.findElement(By.name("uid")).sendKeys("mngr34926"); driver.findElement(By.name("password")).sendKeys("amUpenu"); //Perform Click on LOGIN button using JavascriptExecutor js.executeScript("arguments[0].click();", button); //To generate Alert window using JavascriptExecutor. Display the alert message js.executeScript("alert('Welcome to Guru99');"); >>
  • Successful click on login button and the
  • Alert window will be displayed (see image below).

Execute JavaScript based code using Selenium Webdriver

2) Example: Capture Scrape Data and Navigate to different pages using JavaScriptExecutor.

Execute the below selenium script. In this example,

  • Launch the site
  • Fetch the details of the site like URL of the site, title name and domain name of the site.
  • Then navigate to a different page.
import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.Test; public class JavaSE_Test < @Test public void Login() < WebDriver driver= new FirefoxDriver(); //Creating the JavascriptExecutor interface object by Type casting JavascriptExecutor js = (JavascriptExecutor)driver; //Launching the Site. driver.get("https://demo.guru99.com/V4/"); //Fetching the Domain Name of the site. Tostring() change object to name. String DomainName = js.executeScript("return document.domain;").toString(); System.out.println("Domain name of the site = "+DomainName); //Fetching the URL of the site. Tostring() change object to name String url = js.executeScript("return document.URL;").toString(); System.out.println("URL of the site = "+url); //Method document.title fetch the Title name of the site. Tostring() change object to name String TitleName = js.executeScript("return document.title;").toString(); System.out.println("Title of the page = "+TitleName); //Navigate to new Page i.e to generate access page. (launch new url) js.executeScript("window.location = 'https://demo.guru99.com/'"); >>

Output: When above code is executed successfully, it will fetch the details of the site and navigate to different page as shown below.

Execute JavaScript based code using Selenium Webdriver

[TestNG] Running: C:\Users\gauravn\AppData\Local\Temp\testng-eclipse-467151014\testng-customsuite.xml log4j:WARN No appenders could be found for logger (org.apache.http.client.protocol.RequestAddCookies). log4j:WARN Please initialize the log4j system properly. log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info. Domain name of the site = demo.guru99.com URL of the site = https://demo.guru99.com/V4/ Title of the page = Guru99 Bank Home Page PASSED: Login =============================================== Default test Tests run: 1, Failures: 0, Skips: 0 ===============================================

Execute JavaScript based code using Selenium Webdriver

3) Example: Scroll Down using JavaScriptExecutor.

Execute the below selenium script. In this example,

import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.Test; public class JavaSE_Test < @Test public void Login() < WebDriver driver= new FirefoxDriver(); //Creating the JavascriptExecutor interface object by Type casting JavascriptExecutor js = (JavascriptExecutor)driver; //Launching the Site. driver.get("http://moneyboats.com/"); //Maximize window driver.manage().window().maximize(); //Vertical scroll down by 600 pixels js.executeScript("window.scrollBy(0,600)"); >>

Output: When above code is executed, it will scroll down by 600 pixels (see image below).

Execute JavaScript based code using Selenium Webdriver

Example of executeAsyncScript in Selenium

Using the executeAsyncScript, helps to improve the performance of your test. It allows writing test more like a normal coding.

The execSync blocks further actions being performed by the Selenium browser but execAsync does not block action. It will send a callback to the server-side Testing suite once the script is done. It means everything inside the script will be executed by the browser and not the server.

Example 1: Performing a sleep in the browser under test.

In this scenario, we will use “Guru99” demo site to illustrate executeAsyncScript. In this example, you will

  • Launch the browser.
  • Open site https://demo.guru99.com/V4/.
  • Application waits for 5 sec to perform a further action.

Step 1) Capture the start time before waiting for 5 seconds ( 5000 milliseconds) by using executeAsyncScript() method.

Step 2) Then, use executeAsyncScript() to wait 5 seconds.

Step 3) Then, get the current time.

Step 4) Subtract (current time – start time) = passed time.

Step 5) Verify the output it should display more than 5000 milliseconds

import java.util.concurrent.TimeUnit; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.Test; public class JavaSE_Test < @Test public void Login() < WebDriver driver= new FirefoxDriver(); //Creating the JavascriptExecutor interface object by Type casting JavascriptExecutor js = (JavascriptExecutor)driver; //Launching the Site. driver.get("https://demo.guru99.com/V4/"); //Maximize window driver.manage().window().maximize(); //Set the Script Timeout to 20 seconds driver.manage().timeouts().setScriptTimeout(20, TimeUnit.SECONDS); //Declare and set the start time long start_time = System.currentTimeMillis(); //Call executeAsyncScript() method to wait for 5 seconds js.executeAsyncScript("window.setTimeout(arguments[arguments.length - 1], 5000);"); //Get the difference (currentTime - startTime) of times. System.out.println("Passed time: " + (System.currentTimeMillis() - start_time)); >>

Output: Successfully displayed the passed time more than 5 seconds(5000 miliseconds) as shown below:

[TestNG] Running: C:\Users\gauravn\AppData\Local\Temp\testng-eclipse-387352559\testng-customsuite.xml log4j:WARN No appenders could be found for logger (org.apache.http.client.protocol.RequestAddCookies). log4j:WARN Please initialize the log4j system properly. log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info. Passed time: 5022 PASSED: Login =============================================== Default test Tests run: 1, Failures: 0, Skips: 0 ===============================================

Summary:

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.
  • Illustrated how to click on an element through JavaScriptExecutor, if selenium fails to click on element due to some issue.
  • Generated the ‘Alert’ window using JavaScriptExecutor.
  • Navigated to the different page using JavaScriptExecutor.
  • Scrolled down the window using JavaScriptExecutor.
  • Fetched URL, title, and domain name using JavaScriptExecutor.

Источник

Оцените статью