Thursday, January 28, 2016

Javascriptexecutor to highlight element in Selenium Webdriver

The problem statement for this article is to highlight an element in webPage using Selenium Webdriver. Javascriptexecutor is useful concept in Selenium Webdriver with one of the use being highlighting an element in the page. You can further search down how to use javascriptexecutor in selenium webdriver to perform actions like send key operations, or executing some javascript operation:


Problem Statement:

  • What is Javascriptexecutor?
  • How to highlight an element using JavaScriptexecutor?



What is Javascriptexecutor?

  • JavaScriptexecutor is an interface providing mechanism to execute Javascript through selenium Webdriver.
  • JavaScriptexecutor is used for Javascript injection in the application
  • Through Javascript injection, we can perform different operation including sendkeys operation, clicking on an element or refreshing the html
  • There are two methods to execute javascript using Javascriptexecutor interface:
    • executeScript
    • executeAsyncScript

How to highlight an element using JavaScriptexecutor?

Below code shows how to inject javascript to highlight an element using javascriptexecutor:

 import java.io.File;  
 import org.openqa.selenium.By;
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.WebElement;  
 import org.openqa.selenium.ie.InternetExplorerDriver;  
 import org.openqa.selenium.JavascriptExecutor;  

 public class HighlightElem 
 {  
      static WebDriver driver;  
      public static void main(String[] args) throws InterruptedException 
   {  
           // Connect to the Internet driver server and create an instance of Internet explorer driver.       
           File file = new File("E:\\Testing\\IEDriverServer.exe");  
           System.setProperty("webdriver.ie.driver", file.getAbsolutePath());       
           try{  
                driver = new InternetExplorerDriver();  
           }  
           catch(Exception e)  
           {  
                driver=new InternetExplorerDriver();  
           }  
           //Navigate to the webpage and identify the element to be highlighted.Change the url to valid url  
           driver.navigate().to("https://seleniumbites.blogspot.com");  
     //provide the elemet property to be highlighted
           WebElement element = driver.finndElement(By.linkText("testing"));  
           //highlight the element  
            JavascriptExecutor js = (JavascriptExecutor) driver;  
           js.executeScript("arguments[0].setAttribute('style','border: solid 8px blue')", element);   
           Thread.sleep(2000);  
           js.executeScript("arguments[0].setAttribute('style', arguments[1]);", element, "");  
           element.click();            
      }  
 } 

No comments:

Post a Comment