JavaScript is a Double-edged Sword

Javascript comes handy for manipulating web elements. Actually it is born for it, and that’s why our selenium ancestor (Selenium Core) was written in javascript.  Now with webdriver we can still execute javascript, but remember: javascript is a double-edged sword for automation!

Suppose that you click on an element using javascript as following:

WebElement element = driver.findElement(By.id(“whatever”));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript(“arguments[0].click();”, element);

Then even if the element is invisible,  clicking with javascript will be perfectly fine, and your test will pass. While in real world, user cannot click on an element if he/she cannot view it on screen. Thus your simulation using javascript is false. So: stay away from javaScript when it comes to simulating user interactions. Use WebDriver command instead cos Webdriver fires events from native OS thus mimics the real world user behavior much better than javascript!

When shall we turn to javascript
As far as it is not about simulating user’s interaction with web, you can rest assured and put javascript in use. Many behind-scene dirty works can be done with javascript with no side-effect.    Such as:

  1. Check page loading status
  2. Check ajax call counts/ status
  3. Inject scripts in the page for special purpose
  4. Grab ajax request/response
  5. Highlight the troubled element for screenshot
  6. Scroll page

In summary:

  • Don’t use javaScript when it comes to simulating user interactions. Use WebDriver commands instead
  • Javascript is perfect for condition-checking, like page loading status, ajax call counts/status, or adding customized property to web element for bug identification etc.

Leave a Reply

Your email address will not be published. Required fields are marked *