0

In Selenium WebDriver, there is one method setScriptTimeout(time, unit). If we look at its description, it's

Sets the amount of time to wait for an asynchronous script to finish execution before throwing an error. If the timeout is negative, then the script will be allowed to run indefinitely.

I've two questions here -

  1. I'm confused when this should be used. If someone explains it with an example, it would be really helpful
  2. If I set some time for setScriptTimeout, then before executing each Selenium command(like finding element, clicking on it etc) does it wait for specified time for all javascripts of page to complete it's execution?
Alpha
  • 13,320
  • 27
  • 96
  • 163
  • Sounds more like it waits for the Ajax scripts, the ones that run in the background, even when the page is completely loaded. – LittlePanda Apr 28 '15 at 09:05

1 Answers1

3

The only thing setScriptTimeout does is modify how long Selenium will wait for calls to executeAsyncScript to return. So you use it if you use executeAsyncScript and you want to set a limit beyond which if the script does not call its callback you declare the script dead. To adapt one of the examples in the documentation, if you want to run an XMLHttpRequest and decide that if it takes more than 10 seconds, the test failed, then:

driver.manage().timeouts().setScriptTimeout(10, TimeUnit.SECONDS);

Object response = ((JavascriptExecutor) driver).executeAsyncScript(
   "var callback = arguments[arguments.length - 1];" +
   "var xhr = new XMLHttpRequest();" +
   "xhr.open('GET', '/resource/data.json', true);" +
   "xhr.onreadystatechange = function() {" +
   "  if (xhr.readyState == 4) {" +
   "    callback(xhr.responseText);" +
   "  }" +
   "}" +
   "xhr.send();");

If the script passed to executeAsyncScript does not call callback within 10 seconds, Selenium will raise a timeout.

It specifically does not affect how long Selenium waits for pages to load. Nor does it have anything to do with any asynchronous code that the page executes on its own.

Louis
  • 146,715
  • 28
  • 274
  • 320