[Selenium+java] Execute JavaScript based code using Selenium Webdriver

Source: Internet
Author: User
Tags type casting testng guru99 log4j



Original URL: https://www.guru99.com/execute-javascript-selenium-webdriver.html


Execute JavaScript based code using Selenium Webdriver


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



In the case, these locators does not work with you can use Javascriptexecutor. You can use the Javascriptexecutor to perform an desired operation on a web element.



Selenium support 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.



We'll discuss javascriptexecutor and its execution in Selenium webdriver in this tutorial.



In this tutorial, you'll learn-


    • What is Javascriptexecutor

    • Example demonstrating various operations performed by Javascriptexecutor

What is Javascriptexecutor


Javascriptexecutor is a Interface that helps to execute JavaScript through Selenium webdriver.



Javascriptexecutor provides-Methods "Executescript" & "Executeasyncscript"



To run JavaScript in the selected window or current page.





    1. 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 would execute an asynchronous piece of JavaScript in the context of the currently selected frame or window in Selenium. The JS so executed are single-threaded with a various callback function which runs synchronously.


    1. Executescript


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



The script can return values. Data types returned is


    • Boolean
    • Long
    • String
    • List
    • Webelement.


The basic syntax for Javascriptexecutor is given below:



Syntax:


Javascriptexecutor js = (javascriptexecutor) driver;  Js.executescript (script,arguments);
    • Script–this is the JavaScript, needs to execute.
    • Arguments–it is the Arguments to the script. It ' s optional.
Example demonstrating various operations performed by Javascriptexecutor


Example of Executeasyncscript



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 and Execasync does not block action. It would send a callback to the Server-side testing suite once the script was done. It means everything inside the script would be executed by the browser and not the server.



Example:performing a sleep in the browser under test.



In this scenario, we'll use the "Guru99" demo site to illustrate Executeasyncscript. In this example, you'll





    • Launch the browser.
    • Open site "http://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 (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 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("http://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 (miliseconds) as shown below:



[TestNG] Running:



C:\Users\gauravn\AppData\Local\Temp\testng-eclipse-387352559\testng-customsuite.xml



Log4j:warn No Appenders could is found for logger (org.apache.http.client.protocol.RequestAddCookies).



Log4j:warn 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



===============================================



Example of Executescript



For Executescript, we'll see the three different example one by one.



1) Example:click a button to login and generate Alert window using Javascriptexecutor.



In this scenario, we'll use the "Guru99" demo site to illustrate Javascriptexecutor. In this example,


    • Launch the Web browser
    • Open the site "http://demo.guru99.com/V4/" and
    • Login with Credentials




    • Display Alert window on successful login.
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("http://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‘);");   
    		
    }		
}


Output: When the code is executed successfully. You'll observe


    • Successful click on Login button and the
    • Alert window is displayed (see image below).





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("http://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 = ‘http://demo.guru99.com/‘");			
    }		
}


Output: When above code was executed successfully, it would it would fetch the details of the site and navigate to different page as Shown below.






[TestNG] Running:



C:\Users\gauravn\AppData\Local\Temp\testng-eclipse-467151014\testng-customsuite.xml



Log4j:warn No Appenders could is found for logger (org.apache.http.client.protocol.RequestAddCookies).



Log4j:warn 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 = http://demo.guru99.com/V4/



Title of the page = Guru99 Bank Home page



Passed:login



===============================================



Default Test



Tests Run:1, failures:0, skips:0



===============================================






3) Example:scroll down using Javascriptexecutor.



Execute the below selenium script. In this example,


    • Launch the site
    • Scroll Down by Pixel
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'll scroll down by the pixels (see image below).






Summary:



Javascriptexecutor is used if Selenium Webdriver fails to click on any element due to some issue.


    • Javascriptexecutor provides-Methods "Executescript" & "Executeasyncscript" to handle.
    • Executed the JavaScript using Selenium webdriver.
    • Illustrated how to click on a 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.




[Selenium+java] Execute JavaScript based code using Selenium Webdriver


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.