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

Automating Flipkart via selenium

                                            Hi Folks, we are automating a flipkart site where you will see how to search and filter the product you choose without logging in . import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.Select; import org.testng.annotations.Test; public class flipkart { WebDriver driver ; @Test       public void test()       {   System.setProperty( "Webdriver.chrome.driver" , "chromedriver" );     WebDriver driver = new ChromeDriver();   driver .manage().timeouts().implicitlyWait(5, TimeUnit. SECONDS );   driver .manage().window().maximize();          driver .get( "https://www.flipkart.com" );   ...

Cucumber Datatable testing without using scenario outline and Issues

  Before going through this blog please visit blog The issue you might encounter while running cucumber project- 1.  you have created the cucumber all file in src/test/java and you are trying to  move it in another folder transition might not be smooth, It will give error one fix will led to other.(depends on the setup) 2. If on running a feature file and successfully creating a stepdef file, If application still says that  few steps are still needs to be implemented or all of them(not detecting creation of step definition) then there is a high chance you have mistakenly wrote some other annotation in stepdef when compares to you feature file eg:- feature file @And ( "^user close browser$" ) public   void  user_close_browser()  throws  Throwable { Stepdef:-             @Then ( "^user close browser$" ) public   void  user_close_browser()  throws  Throwable { driver .quit(); 3. Duplicate S...