Leapwork has different building blocks to interact with web page elements. But sometimes due to some issues in the application, the interaction with web elements does not work as expected.
In order to mend this situation, there is a workaround that can be used as an alternative to using the regular building blocks like Click Web Element, Get Web Text etc.
A Run Web JavaScript building block is used to execute a piece of JavaScript in an open browser window. This can, for instance, be used to trigger events on a web page. Please note that this block only works with browser windows that were previously opened using the Start Web Browser block or their “child” windows.
Clicking An Element With JavaScript :
You can click an element with JavaScript once you have the locator to that element. The element can be located in multiple ways using JavaScript.
The easiest way to find an HTML element in the DOM [Document Object Model], is by using right-click and selecting inspect element on the browser. Then using the element id of the mentioned element in the JavaScript block. Eg. document.getElementById("<Element ID>");
There are other ways to achieve that, such as using a tag name, class name, or most importantly the CSS Selector. Once you have the element locator you need to use the click() function provided in JavaScript. Here is an example :
Here we have utilized the CSS Selector for finding the element and the command goes by:
document.querySelector("<CSS Selector>").click();
This will ensure the element with the specified selector is clicked by JavaScript.
Similarly, some other methods would be :
document.getElementsByClassName("<Class name>")[0].click();
document.getElementsByTagName("<Tag Name>")[0].click();
Note :
1.Since document.getElementsByClassName/document.getElementsByTagName returns an array-like object of all the child elements which have all of the given class names/tag names, you need to define the index to perform any operation as used above i.e clicking first element[0] in the array.
JavaScript click does not wait for any element states like Visible/Clickable etc. It will go ahead and click the element without being concerned about the element present state.
Getting the text of a web element using JavaScript :
You can use the innerText property to extract the text contained in the particular element. The innerText property returns the text content of the specified node, and all its descendants.
Eg. return document.getElementById("myBtn").innerText;
The return statement returns the text selected and which can be captured by any subsequent block from the result node. Here we have used the text as a log message in the image above.
Note : Please use the "Result as" field with "Text" value, otherwise it will lead to errors.
Visit Run Web JavaScript documentation to know more about the block.
For any clarification, please contact our Priority Support.
Comments
0 comments
Please sign in to leave a comment.