Ricardo Peres Ricardo Peres - 5 months ago 65
Node.js Question

Waiting for JavaScript event with Selenium

I am building an automation framework on top of Selenium (Node.js) consisting on a number of steps.
Each step follows the previous one, after it completes, returning a promise (like the one returned by Selenium's driver.click(), etc).
Is it possible to wait for a JavaScript event to trigger on the browser? If so, what is the pattern to follow?

Answer

Use .executeAsyncScript to wait for an event to occur :

driver.executeAsyncScript(function(callback) {
  window.addEventListener('message', function onmessage() {
    window.removeEventListener('message', onmessage);
    callback();
  });
});

The doc:

http://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/lib/webdriver_exports_WebDriver.html#executeAsyncScript

Comments