JavaScript Executor

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.

20161215_163858
JavaScript Executioner enjoying a night out at the Jotemheim tavern

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:

  1. Open DevTools inside your browser (F12)
  2. Go to the Elements tab  elements
  3. Click on the arrow arrow
  4. Point at the “Sign In” button to get the ID

elementid

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:

  1. Open up DevTools
  2. Navigate to the Console tab console
  3. Paste your JavaScript next to the carrot >
  4. Hit enter to run it:

01_console

You should see the button get clicked and bring you to the next page:

02_signin

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();