0% found this document useful (0 votes)
33 views3 pages

JavaScript and Selenium Element Interaction

This document discusses different ways to interact with elements on a webpage using JavaScript in Selenium, including the differences between using WebDriver clicks versus JavaScript clicks. It recommends using WebDriver clicks as much as possible, but using JavaScript clicks when WebDriver clicks do not work, as JavaScript clicks do not check for element visibility and size before clicking. It also provides examples of using JavaScript to scroll the page, set element values, and take screenshots of the full page.

Uploaded by

shivanibharti
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views3 pages

JavaScript and Selenium Element Interaction

This document discusses different ways to interact with elements on a webpage using JavaScript in Selenium, including the differences between using WebDriver clicks versus JavaScript clicks. It recommends using WebDriver clicks as much as possible, but using JavaScript clicks when WebDriver clicks do not work, as JavaScript clicks do not check for element visibility and size before clicking. It also provides examples of using JavaScript to scroll the page, set element values, and take screenshots of the full page.

Uploaded by

shivanibharti
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

in javascript window and document are two different things

window is the window screen and document is the webpage loaded


Javascript has 3 scroll menthods that are utilized by window
[Link](0,900)
[Link](0,90)
[Link](2,6)-->negative will scroll upwards
And document has few methods to find element
[Link]("return [Link]('skjks');");
[Link]("return [Link]('';");
[Link]("return [Link]('';");
[Link]("return [Link]
Only id element will be singular rest all are list of webelement

“JavaScript (“JS” for short) is a full-fledged dynamic programming language that,


when applied to an HTML document, can provide dynamic interactivity on websites.”
JavascriptExecutor js = (JavascriptExecutor) driver;
[Link]([Link]("//span[contains(text(),'Solutions')]")).click();
[Link]([Link]("//a[contains(text(),'Geolocation
Testing')]")).click();
[Link]("[Link](0,40)");
((JavascriptExecutor)driver).executeScript(“arguments[0].click()”, element);
[Link]("arguments[0].value='selenium'", searchBox);
JavascriptExecutor executor = (JavascriptExecutor)driver;
[Link]("[Link]("textbox_id").value='new value';);

Difference between WebDriver click() and JavaScript click() method in Selenium.


We already have enough locators in Selenium webdriver, which help us in identifying
web elements on a web page. But sometimes, these locating strategies fail when web
element is hidden or it is deeply nested. When we perform any action on these types
of web elements, it doesn’t work. If an y website has a lot of AJAX calls, in that
case also javascript locating commands are very useful.

We can perform click on a web element of a web page in two ways:-

Using WebDriver click – [Link]()


Using JavaScript click –
((JavascriptExecutor)driver).executeScript(“arguments[0].click()”, element);
( Note- driver is a WebDriver instance.)
So question must be arised in your mind, which is better and when to use.

Since Selenium 3, maximum browser are providing their respective browser driver
which implements WebDriver API. Selenium communicates to these browser drivers
through HTTP commands and these drivers communicates natively with browser.
Official documentation of Selenium says:-
“Selenium-WebDriver makes direct calls to the browser using each browser’s native
support for automation. “

So we can say that the way chrome browser allows a click on a web element may be
different from other browsers.

So when we click on a webelement using Selenium WebDriver , it checks two


preconditions before clicking:-

The element must be visible.


It must have a height and width greater than 0.
If preconditions are not satisfied, you will get exceptions stating element is not
clickable or interactable. Refer click() method in official document here.
But in JavaScript clicks does not check these preconditions before clicking. The
[Link]() method simulates a mouse click on an element. When click() is
used with supported elements (such as an <input>), it fires the element’s click
event. Reference here.

So, JavaScript could click on a web element which may not be clickable by WebDriver
API. So use WebDriver click as much as possible and go for JavaScript click when
WebDriver click does not work.

WebDriver APIs are designed to simulate the actions which a real user will perform
on front end of application. When we go for JavaScript, this is not taking into
consideration. JavaScript ways may not catch the bugs which is main goal of
automation scripting.

JavaScript operations may not call actions sometimes. Suppose when you click on a
button, some popup should appear. That can be relate as onClick event. You may
encounter these issues. These issues will not come if you use WebDriver APIs.

I would like to share a problem I faced while automating. There was a Date of birth
field which takes input from user and calculates actual age. I typed DOB using
Javascript way and it was not calculating actual age and event set on DOB field was
not called.

------------------------------------------------------------------------------
how to take Scrren shot of whole page
// Down casting driver to JavascriptExecutor
JavascriptExecutor js = (JavascriptExecutor) driver;

// It returns height of view part. You can say it as page height. When
you click on page down key
// Page scroll by one page.
long pageHeight= (long)[Link]("return [Link]");
[Link]("Page height: "+pageHeight);

// It is how much you can scroll. It is height if you scroll, you will
reach to bottom of page.
long scrollableHeight= (long)[Link]("return
[Link]");
[Link]("Total scrollable height: "+scrollableHeight);

// Finding number of pages. Adding 1 extra to consider decimal part.


int numberOfPages=(int) (scrollableHeight/pageHeight)+1;
[Link]("Total pages: "+numberOfPages);

// Now scrolling page by page


for(int i=0;i<numberOfPages;i++)
{
[Link](driver,
"Page "+(i+1));
[Link]("[Link](0,"+pageHeight+")");
[Link](2000);
}

public static String CaptureScreenShotWithTestStepName(WebDriver driver,


String testStepsName)
{
try{
// down casting WebDriver to use getScreenshotAs method.
TakesScreenshot ts= (TakesScreenshot)driver;
// capturing screen shot as output type file
File screenshotSRC= [Link]([Link]);
// Defining path and extension of image
String
path=[Link]("[Link]")+"/ScreenCapturesPNG/"+testStepsName+[Link]
entTimeMillis()+".png";
// copying file from temp folder to desired location
File screenshotDest= new File(path);
[Link](screenshotSRC, screenshotDest);
return path;
}catch(Exception e)

-----------------------------------------------
how to set calender date if it allows you to put date manually as well as using
calender
public static void setDateUsingJavaScriptInCalendar(WebDriver driver, String value,
WebElement calLocator)
{
JavascriptExecutor jse= (JavascriptExecutor)driver;
String script= "arguments[0].setAttribute('value','"+value+"');";
[Link](script, calLocator);
}
public static void main(String[] args) {

[Link]("[Link]",
"./exefiles/[Link]");
WebDriver driver= new ChromeDriver();
[Link]().window().maximize();
[Link]("[Link]
[Link]");

// Locating departure date calendar


WebElement departCal= [Link]([Link]("datepicker"));

[Link](driver,"10/09/2
017",departCal);

Common questions

Powered by AI

JavaScriptExecutor allows execution of JavaScript code in Selenium, facilitating operations like clicking on elements, changing element values, and finding elements by ID, class, or tag when WebDriver fails due to hidden elements or AJAX calls . It can be used to scroll through a page or set attributes directly on elements, which WebDriver might not handle due to visibility or interaction restrictions .

JavaScript's click() method simulates a mouse click on an element without checking preconditions like element visibility or size, which allows clicks on elements that WebDriver's method may not click . WebDriver's click is preferred for simulating real user interactions and is more consistent in triggering associated events like onClick . Use JavaScript click when WebDriver click fails due to hidden or nested elements .

WebDriver click actions are designed to simulate actual user interactions based on the browser's native support, ensuring element visibility and size, which is crucial for capturing bugs related to user experience . JavaScript clicks can bypass these checks, potentially missing out on user-related bugs and action triggers like popups tied to onClick events .

The window object represents the browser's window and uses scroll methods like window.scrollBy and window.scrollTo for scrolling actions . The document object represents the webpage and allows element selection with methods like document.getElementById or document.getElementsByClassName, crucial for finding and interacting with web elements .

Browser-specific drivers in Selenium allow communication with different browsers using their native automation capabilities, ensuring tests run consistently across various environments without relying solely on JavaScript hacks. This leads to better cross-browser compatibility and reduces the dependency on workarounds, thus aligning more closely with end-user experience .

Screenshots during Selenium tests can be captured by scrolling through the page using JavaScriptExecutor and taking screenshots page by page, leveraging methods such as getScreenshotAs from TakesScreenshot interface for full-page documentation. This ensures comprehensive verification of web elements and layouts .

Using JavaScriptExecutor, a date can be set in a calendar component by altering the DOM directly with the setAttribute method to assign a date value. This is preferred over frontend interactions when dealing with non-standard calendar widgets that do not expose user-friendly selectors .

JavaScriptExecutor can access and interact with web elements affected by AJAX by executing JavaScript code that WebDriver alone cannot handle due to AJAX-related timing issues. This allows actions on dynamically changing content or hidden elements, making scripts more resilient to AJAX asynchronous updates .

Scrolling strategies in Selenium involve using JavaScriptExecutor to calculate the page height and scrollable height. By determining the number of pages through these calculations and using window.scrollBy to scroll page by page, the entirety of long content can be managed effectively .

JavaScript operations may fail when they do not trigger bound UI events, such as onClick, that are necessary for automation scripts to accurately reflect user interactions. This can happen if JavaScript directly manipulates elements without firing associated actions, as seen in input fields where events do not get triggered .

You might also like