Adjust the duration of the script timeout in Selenium for JavaScript programming

Currently, I am developing a function in JavaScript within the Selenium WebDriver framework to scroll on a website for a specific duration. The issue I am facing is that the default script timeout is approximately 15 seconds before it raises a ScriptTimeoutError. While there is ample information available on how to adjust this timeout in languages like Java with Selenium, documentation for the JS library is severely lacking.

To demonstrate the error, the test code below will trigger a ScriptTimeoutError after around 25 seconds:

const { Builder, By, Key } = require("selenium-webdriver");

async function example() {
  let driver = await new Builder().forBrowser("chrome").build();

  await driver.get("https://google.com");

  await driver.executeScript(`
  
  await new Promise((resolve) => setTimeout(resolve, 30000));
  
  `);
  console.log("DONE!");
}

example();

Below is the stack trace showing the ScriptTimeoutError:

ScriptTimeoutError: script timeout
  (Session info: chrome=118.0.5993.118)
    at Object.throwDecodedError (path\selenium-webdriver\lib\error.js:524:15)
    at parseHttpResponse (path\selenium-webdriver\lib\http.js:601:13)
    at Executor.execute (path\selenium-webdriver\lib\http.js:529:28)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async Driver.execute (path\selenium-webdriver\lib\webdriver.js:745:17)
    at async example (path\tests\test 4.js:8:3) {
  remoteStacktrace: '\tGetHandleVerifier [0x00007FF705638EF2+54786]\n' +

Answer №1

After dedicating numerous hours to research, I stumbled upon the solution by pure chance. Within the WebDriver, there exists a function called manage(), which grants access to various useful functions for controlling the selenium server. Among these is setTimeout(), which accepts an object defining different timeouts for the webdriver (script, pageLoad, implicit). To set the timeout, an await statement must be used within an async function.

await driver.manage().setTimeouts({ script: 60000 });

The setTimeout function expects a JavaScript object to define timeouts:

 {
     implicit: time-in-milliseconds,
     pageLoad: time-in-milliseconds,
     script: time-in-milliseconds
}

Other handy functions available in the manage class:

Final Solution:

let webdriver = require("selenium-webdriver");

async function example() {
  // create driver
  let driver = await new webdriver.Builder().forBrowser("chrome").build();

  //   This function sets the script timeout to 60 seconds 
  //   Other timeouts can also be set using this function with an object:
  //   {
  //       implicit: TimeInMS,
  //       pageLoad: TimeInMS,
  //       script: TimeInMS
  //    }
  await driver.manage().setTimeouts({ script: 60000 });

  // This function retrieves the different timeouts for the selenium server
  //   { implicit: 0, pageLoad: 300000, script: 35000 }
  const timeouts = await driver.manage();
  console.log(timeouts);

  // Go to website
  await driver.get("https://bing.com");

  // Driver executes a script for 35 seconds
  await driver.executeScript(`
  
    await new Promise((resolve) => setTimeout(resolve, 35000));
  
  `);

  console.log("DONE!");
}

example();

Answer №2

Consider running your script asynchronously by using driver.executeAsyncScript(). This way, you can ensure that it waits for the promise to be resolved before continuing. Additionally, if you have a short timeout threshold, you can set the script timeout using

driver.manage().timeouts().setScriptTimeout()
.

Keep in mind that setScriptTimeout() will specifically impact async scripts.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Looking for assistance with creating a D3 bar chart that involves selecting a specific year and crime category? Let me help

I am still learning D3 and I'm facing a challenge while trying to create a bar chart. My idea is to first select the YEAR radio button, then choose the CRIMEHEAD option, and finally the bar chart should be displayed. Here's my thought process: I ...

Displaying JSON as a table using React JS

I can't seem to display JSON data in a table using the useState hook in React, and I'm not sure why. Here's a snippet from my React file: {` import React, { useState } from 'react' import "../styling/Classes.css"; import data ...

Incorporate a JavaScript script into an Angular 9 application

I have been experiencing issues trying to add a script.js file to angular.json and use it in one component. Adding a script tag directly to my HTML file is not the ideal solution. Can someone suggest an alternative approach or point out what I may be missi ...

What is the best way to integrate ES6 ReactJS code into an Express application?

I am trying to initially render my ReactJS application on the server using ExpressJS. Although I have been able to import ES6 modules using require(), the module crashes upon loading because it contains ES6 code (ES6 import and export). Index Route var ...

python execute the driver.quit() method within the except block using selenium

I have an application that needs to close the driver if it throws an exception. I attempted the code below, but it is still throwing an exception. Here is my code, where url is the URL I want to open: driver=webdriver.Firefox() try: driver.get(url) e ...

I am experiencing issues with buttons not appearing on screen while attempting to establish a connection with Dropbox through the use

I am currently working on a lab project and looking to utilize Javascript to connect to Dropbox. Despite checking for syntax errors, the code I have written does not display the buttons as expected. You can view the current code setup in this JSFiddle: ht ...

Navigating through sibling elements can be accomplished by using various methods in

Can someone help me figure out how to assign unique IDs to 6 different Div elements as I step through them? The code snippet below is not working as expected, giving all Divs the same ID. What is the correct way to accomplish this task? $('#main-slid ...

The attempt to use RTSP streaming with Node.js for an IP camera and JSMPEG

Having an issue connecting to an IP camera where the image does not appear properly When running node app.js "frame= 1970 fps=2.0 q=7.6 size= 22457kB time=00:16:25.00 bitrate= 186.8kbits/s dup=0 drop=3 speed=1.01x" Upon executing index.html &qu ...

Accessing the hashtag portion of the URL in Nuxt

this.$route.path retrieves the URL without the hashcode at the end. Is there a way to obtain the hash part of the URL or the entire URL so that I can properly separate the hash part? Just to clarify, for a URL like https://example.com#test, I am trying to ...

Getting all inline styles from an HTML string using JavaScript

(JavaScript) I am working with an html email template stored as a string. Is there a way to extract all the inline styles used in the template? For instance, if I have this input: <div style="min-width:300px;max-width:600px;overflow-wrap:break-word ...

The assignment of ajax success data to variables results in an error because data[0] is not defined

Having some trouble retrieving and assigning data from a database in JavaScript using AJAX to call a PHP script with a MySQL query. Although the AJAX request is successful, when trying to store the data into variables, they appear as undefined or NaN in th ...

I'm tired of repeatedly typing driver.findElement(By.xpath("")) over and over

Hey there! Check out this code snippet below. I'm trying to create a function that allows me to pass the XPath value, so I don't have to keep writing driver.findElement(By.xpath("")) repeatedly. sendKey("//*[@id='lead_source']", "Exist ...

Creating JavaScript accessors for Java beans

Is there a Java framework available that can automatically generate JavaScript code to access backend beans? For instance, suppose I have a Spring service named TestService: public interface TestService { public static class UserDTO { public S ...

What is the process behind __doPostback generating a URL on an ASP.NET website?

Can you please check out the following URL: When you select "Exhibitor A to Z" from the dropdown menu and click search, a javascript function is triggered for each link (javascript:__doPostBack('ctl00$MainContent$grdExhList$ctl00$ctl04$lnkExhLink&ap ...

Creating dynamic buttons with event listeners and parameters in JavaScript using jQuery

I am attempting to dynamically create and append buttons to an HTML page with defined events using the following code: var mdata = JSON.parse(data); mdata.forEach(function(k) { $("#routesPage").append("<button class='accordion' onclick=&a ...

What is the best way to continuously execute the 'onclick' function using AJAX inside a specific ID?

My challenge involves implementing a new AJAX upload feature to insert a data element from the onClick event in multiple rows. The issue I am facing is that it works fine for the first row, but when I add subsequent rows, the function no longer works upon ...

losing track of the requested parameters while working asynchronously with Firestore documents

Today is my first time experimenting with firestore and express. Here is the code snippet I am using: app.post('/api/create', (req, res) => { (async () => { try { console.log(req.body); //the above consle.lo ...

Utilizing a Clear Button to Reset Specific Fields in a Form Without Clearing the Entire Form

I am currently working on a multipart form that includes 'Name', 'Email', and 'Phone Number' fields. It's important to note that the phone number field is actually composed of 10 individual single-digit fields. To enhan ...

Can Selenium handle compiled DLLs created with Coded UI?

I have been attempting to integrate Coded UI compiled Dlls into my Selenium project. I created a Class Library Project in Visual Studio where I defined a class with a method to highlight the "Save as window" like so: namespace CreateDll { public cl ...

Selenium experiences a delay when attempting to switch to a frame

After updating Selenium Webdriver to 2.44 in order to use it on Firefox ESR 32, I encountered a new issue. When trying to switch to a frame that hasn't fully loaded yet, the program hangs. The website I am testing has multiple iframes and switching be ...