JavaScript Executioner was a high court executioner who challenged Conan the Barbarian to a drinking contest. After it was discovered that he filled Conan’s meadhorn with sea-water, he was exiled from the land of Hyrkania. He was forced to wander the desolate wastelands, where he foraged for insects and wrote JavaScript on stone tablets. In this post we will explore his less popular cousin, JavaScript Executor.
When you are writing automation scripts to test a website, you will find that some buttons and elements are problematic when trying to execute a Click() action. For example, your script may think that it has performed a Click() action on a button called “Sign In“, yet you can clearly see that the Click() is not happening. As a result, your test script could be hanging or throwing an unexpected error.
Since this element is being difficult, we can use JavaScript to force a Click() event. First we need to find the ID of the button that we want to click. To do this:
- Open DevTools inside your browser (F12)
- Go to the Elements tab
- Click on the arrow
- Point at the “Sign In” button to get the ID
Now that we have the ID, we can write a simple JavaScript to perform the Click() action.
document.getElementById('a-autoid-0-announce').click()
document = this is the HTML document object
getElementById = this method is used to identify an element using its ID attribute
To test your JavaScript:
- Open up DevTools
- Navigate to the Console tab
- Paste your JavaScript next to the carrot >
- Hit enter to run it:
You should see the button get clicked and bring you to the next page:
If the Click() event worked, your JavaScript has been validated and is ready to use. Now you can paste it into your automation script to replace a standard Click() action.
QTP/UFT example:
Browser("Browser").Page("Page").RunScript("document.getElementById('a-autoid-0-announce').click();")
C# example (WebDriver):
((IJavaScriptExecutor)driver).ExecuteScript("document.getElementById('a-autoid-0-announce').click();");
Java example (WebDriver):
((JavascriptExecutor)driver.get()).executeScript("document.getElementById('a-autoid-0-announce').click();");
JavaScript example (WebDriver):
driver.findElement(By.id('a-autoid-0-announce')).click();