Selenium and asynchronous JavaScript calls

后端 未结 2 2023
栀梦
栀梦 2020-12-30 15:00

i\'m quite new to Selenium and JavaScript-callback functions and i have a big issue I can\'t solve myself. I need a specified variable using JavaScript. If I open the page w

2条回答
  •  离开以前
    2020-12-30 15:28

    Though this is almost same as what @Louis said.You have to set the setScriptTimeout beforehand for the script to pass.

    The default timeout for a script to be executed is 0ms. In most cases, including the examples below, one must set the script timeout WebDriver.Timeouts.setScriptTimeout(long, java.util.concurrent.TimeUnit) beforehand to a value sufficiently large enough.

    Below is an example for which I'm waiting for 10 seconds to return a string

      driver.manage().timeouts().setScriptTimeout(20, TimeUnit.SECONDS);//important
    
        JavascriptExecutor executor = (JavascriptExecutor) driver;
        String val = (String) executor.executeAsyncScript(""
                + "var done=arguments[0]; "
                + "setTimeout(function() {"
                + "   done('tada');"
                + "  }, 10000);");
    
        System.out.println(val);
    

提交回复
热议问题