Skip to main content

JavaScript- Highlighting the element and creating Alert

        

Java Script Executor.

Javascript is an interface that helps to execute javascript through Selenium Webdriver

If the locators like Xpath and css do not work then you can use Java script executor, you can use javascript  to  highlight element and to create alerts and handle dynamic ID's

Syntax is as below.

JavascriptExecutor js = (JavascriptExecutor) driver;  
js.executeScript(Script,Arguments);

 

JavaScriptExecutor Methods

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

  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 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 
  • Boolean
  • Long
  • String
  • List
  • WebElement. 
Code for execution

import java.util.concurrent.TimeUnit;


import org.openqa.selenium.By;

import org.openqa.selenium.JavascriptExecutor;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.chrome.ChromeDriver;

import org.testng.annotations.Test;


public class Javascriptdemo {

 @Test 

    public void test()

    {

  System.setProperty("Webdriver.chrome.driver", "chromedriver");

  WebDriver driver = new ChromeDriver();

Code 1- creating an alert using java script on google homepage

 driver.get("https://www.google.com/");

 driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);

 driver.manage().window().maximize();  

//converting Webdriver to Java script executor

JavascriptExecutor js =(JavascriptExecutor)driver;

js.executeScript("alert('welcome to demo')");  

Please find the video on alert here      

Code 2-Highlight the element using Javascript in Facebook


driver.get("https://www.facebook.com/");

driver.findElement(By.id("email")).sendKeys("Your email Id");;

driver.findElement(By.id("pass")).sendKeys("Your password");;

WebElement button= driver.findElement(By.id("u_0_b"));

//Flash method has been created below you can reuse the  code in your project

//it will highlight the login button in this case

  flash(button,driver);

Please find the uploaded video on highlighting the login button of Facebook here

//border method has been created below you can reuse the  code in your project

//it will create red border around login button

          border(button,driver);

    }

Please find the video on border creation "login button" of Facebook here

   

Code 3Creating  a flash method   ...

public static void flash(WebElement element, WebDriver driver){

JavascriptExecutor js =(JavascriptExecutor)driver;

String bgcolor = element.getCssValue("backgroundColor");

for(int i=0; i<100; i++){

changeColor("rgb(0,200,0)",element,driver);

changeColor(bgcolor,element,driver);

}

}

public static void changeColor(String color,WebElement element, WebDriver driver){

JavascriptExecutor js =(JavascriptExecutor)driver;

js.executeScript("arguments[0].style.backgroundColor='"+color+"'", element);

try{

Thread.sleep(20);

}

catch(InterruptedException e){

}

}

Code 4Creating  a border method  ...

public static void border(WebElement element, WebDriver driver){

JavascriptExecutor js =(JavascriptExecutor)driver;

js.executeScript("arguments[0].style.border='3px solid red'", element);

}

}


Using the above code you can create a login on Facebook 

1. Enter username
2. Enter password
3. Highlight Login button
4. Take screenshot.
5. If login is not successful (Reason can be wrong username and password)
6.Take screenshot of error



@Test

public void test() throws IOException

{

System.setProperty("Webdriver.chrome.driver","chromedriver");

 WebDriver driver = new ChromeDriver();

 driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);

 driver.get("https://www.facebook.com");

 driver.manage().window().maximize();

 driver.findElement(By.id("email")).sendKeys("topriyankac@gmail.com");

//enter wrong password

 driver.findElement(By.id("pass")).sendKeys("12345678"); 

 WebElement button= driver.findElement(By.id("u_0_b"));

//highlighting the login button

 border(button,driver);

//Taking a screenshot

 TakesScreenshot ts1=(TakesScreenshot)driver;

File src1 = ts1.getScreenshotAs(OutputType.FILE);

// Screenshot will be saved in folder fbhighlight already created in desktop and screenshot name will be screenshot1

FileUtils.copyFile(src1, new File("/Users/priyankac/Desktop/fbhighlight/screenshot1.png"));

//Now click on login button

 button.click();

//It will fetch the title of the page

String title = driver.getTitle();

//if the title is still Facebook login page that mean user did not navigate to the next window

  if(title.contentEquals("Facebook – log in or sign up"))

    {

//moving on to next window unsuccessful

System.out.println("launch unsuccessful");

//Take the screenshot of the error message.

TakesScreenshot ts2=(TakesScreenshot)driver;

File src2 = ts2.getScreenshotAs(OutputType.FILE);

// save it in same folder fb highlight with name screenshot 2

FileUtils.copyFile(src2, new File("/Users/priyankac/Desktop/fbhighlight/screenshot2.png"));

}

else {

System.out.println("launch successful");


     }

    

}


}


To check the above execution click here

Comments

Popular posts from this blog

Cucumber - Execution of test cases and reporting

Before going through this blog please checkout blog on   Cucumber Fundamentals Cucumber is testing tool which implements BDD(behaviour driven development).It offers a way to write tests that  anybody can understand, regardless of there technical knowledge. It users Gherkin (business readable language) which helps to  describe behaviour without going into details of implementation It's helpful for  business stakeholders who can't easily read code ( Why cucumber tool,  is  called  cucumber , I have no idea if you ask me I could have named it "Potato"(goes well with everything and easy to understand 😂) Well, According to its founder..... My wife suggested I call it  Cucumber  (for no particular reason), so that's how it got its  name . I also decided to give the Given-When-Then syntax a  name , to separate it from the  tool . That's why it's  called  Gherkin ( small variety of a cucumber that's been pickled. I...

Jmeter 5.4.1- Config Elements - Part-03

  Part-01- Installation of Jmeter and HTTP's Recorder click  here Part 02--Previous blog on Assertion Config elements in Jmeter are used to configure or modify the samplers requests made to the server. These elements are added at the same or higher level of the samplers that we want to configure  Let' start with  CSV data config As the name suggest it used to read data from CSV first we need to put data in variables and then use the variables in sampler request. create a new test plan add CSV data set config Add a Thread Group and then add Sampler "Java Request"  Create a CSV file  with some data (Name and Data) and save it  Now go to Jmeter CSs data set config browse and upload the css file create Make few more changes in place of  variable name - Name and Dept Ignore first line - True Delimeter - \t (as suggested) Now move on the Sampler-" Java Request" and rename it with header elements of CSV As we have Name and d...

Beginners tutorial -:working with JMeter in Mac and windows - Part-01

  Prequisite   you should have Java downloaded in your system with Home path set under environment variables.(as of today Java version 8 and higher are required fro jmeter ) for help check out this link Note Always run the jmeter on your secondary browser,  if you give the primary browser for proxy settings then your internet connection will be disrupted for the browser as well as system For ex if you have chrome and firefox and your primary or default browser is chrome then do all the proxy setting in firefox so it won't hamper the system Internet connection  if you have safari as your default browser in your mac os then set proxy in chrome/firefox  MAC Download jmeter from the link  here click on the hypelink under section Binaries  "Apache JMeter( 5.3 ). tgz" file  for Mac   Tar file will get downloaded Double click on the tar file to unzip  once you open the folder  got to bin and search for jmeter.sh file this is a executa...