JavaScriptExecutor in Selenium - Bug Reaper

                  Bug Reaper

Lean about Automation Testing,Selenium WebDriver,RestAssured,Appium,Jenkins,JAVA,API Automation,TestNG,Maven, Rest API, SOAP API,Linux,Maven,Security Testing,Interview Questions

Monday 24 February 2020

JavaScriptExecutor in Selenium

Sometimes you will see Selenium commands not working properly, in that case we can use JavaScript Executor.

JavaScriptExecutor is an Interface that helps to execute JavaScript through Selenium Webdriver.
Example:
1.)Scrolling in selenium sometimes we face problem, in that case we use  JavaScript Executor.
2.) Handling Hidden Elements.
3.)Element is not clickable, other element would receive click.
4.) Screenshot of required web element is not captured.

EveryBrowser executes JavaScript, so we can use JavaScript Executor to handle browser events.

Example

scrollIntoView() of Javascript:

Javascript provides an another useful method to scroll named scrollIntoView(). This method scrolls the element on which it’s called into the visible area of the browser window. It means, you no need to pass co-ordinates of elements if you use this method. You just locate element and call this method on located element. Javascript automatically scroll till the element is visible on browser’s visible area.

/** * scroll element to bring in view, scroll down the page * * @param element */public void scrollElementIntoView(WebElement element) {
    try {
        ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(false);", element);
        Thread.sleep(1000);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Scrolling 

Javascript provides below methods to scroll:

scrollBy (x-coord, y-coord)
scrolTo (x-coord, y-coord)
scroll (x-coord, y-coord)

x-coord is the pixel along the horizontal axis of the document that you want displayed in the upper left.

y-coord is the pixel along the vertical axis of the document that you want displayed in the upper left.

Difference Between ScrollBy, ScrollTo and Scroll Methods Of Javascript

Scroll method is same as ScrollTo method.

ScrollTo scrolls by pixels considering current scrolled position and compares with (0,0) and decides whether to scroll or not.

ScrollBy always scrolls up or down further from current position

Therefore we use ScrollBy if we want continuous Scrolling and


Note: If you see window.scrollTo(0,500) command in Console. Observe the vertical scroll bar now. You will see vertical scroll bar has been scrolled by 500 pixels vertically because you have passed 500 as value of Y co-ordinates.
Observe that I typed window.scrollTo(0,500) two times  even after that Scroll doesn't happen again because window.scrollTo(0,500) only scroll to that coordinates and doesn't happen again


Note: If you see window.scrollBy(0,500) command in Console.I typed window.scrollBy(0,500) multiple times  and  Observe that it kept scrolling  vertically and Scroll bar reached to end of page



Javascript provides below command to locate web elements on a web page which are given below:

getElementById
getElementsByClassName
getElementsByName
getElementsByTagName


USAGE of getElementById

// Down casting driver to JavascriptExecutor
JavascriptExecutor js= (JavascriptExecutor)driver;

// Down casting to WebElement because executeScript return a type of Object
WebElement element= (WebElement) js.executeScript("return document.getElementById('uploadBtn')");

USAGE of getElementsByClassName

// Down casting driver to JavascriptExecutor
JavascriptExecutor js= (JavascriptExecutor)driver;

// Down casting to List<WebElement> because executeScript return a type of Object
List<WebElement> element= (List<WebElement>) js.executeScript("return document.getElementsByClassName('locator')");

// Getting text
System.out.println(element.size());


Difference between window and document in javascript:

“window” and “document” are object in javascript which are not same. When we launch a browser, what you see (excluding header , footer i.e. highlighted below) is “window”

The window object represents the browser window.

The document object represents the HTML document loaded in that window.


window is the execution context and global object for that context's JavaScript
document contains the DOM, initialized by parsing HTML

Javascript is the alternative for sendKeys method. Sometimes we encounter some text box which is nested and selenium is not able to interact.

HTML web element has an attribute called “value” , so if we set this value to some text , this will be set for that web element


Example

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

WebElement searchBox= driver.findElement(By.name("q"));

// Down casting driver to JavascriptExecutor
JavascriptExecutor js = (JavascriptExecutor) driver;

// Setting value for "value" attribute
js.executeScript("arguments[0].value='selenium'", searchBox);


Upload In Selenium Using JavaScript

Example of DOM Element below

<input _ngcontent-c17="" accept="image/png,image/jpeg" hidden="" id="banner" name="banner" type="file">


Here if you notice the tag is input and the attribute is hidden
In Selenium you will get exception as element is not visible.

If you try  JavaScript ways to set the value, you will get exception as element can not be interacted. Since element is hidden, so none of the ways will work.

Sample Code
WebElement searchBox= driver.findElement(By.id("files"));

// Down casting driver to JavascriptExecutor
JavascriptExecutor js = (JavascriptExecutor) driver;

// Setting value for "style" attribute to make input tag visible
js.executeScript("arguments[0].style.display='block';", searchBox);

searchBox.sendKeys("Path for the image");
}

Perform Click

/Perform Click on WebElement using JavascriptExecutor
        js.executeScript("arguments[0].click();", WebElement );

Fetching Domain Name

//Fetching the Domain Name of the site. Tostring() change object to name.
        String DomainName = js.executeScript("return document.domain;").toString();

Fetching URL
//Fetching the URL of the site. Tostring() change object to name
        String url = js.executeScript("return document.URL;").toString();

Fetching TitleName 
//Method document.title fetch the Title name of the site. Tostring() change object to name
       String TitleName = js.executeScript("return document.title;").toString();

Navigate to new Page

//Navigate to new Page i.e to generate access page. (launch new url)
      js.executeScript("window.location = 'http://bugreaper.blogspot.com/'");

No comments:

Post a Comment