简体   繁体   English

如何使用 Selenium WebDriver 中的 JavaScriptExecutor 在加载 js 脚本时执行 js function

[英]how to execute js function on load of a js script using JavaScriptExecutor in Selenium WebDriver

I'm trying to execute a js function after js script gets loaded on an HTML page.在 js 脚本加载到 HTML 页面后,我正在尝试执行 js function。 But the issue is js script takes some time to load on the HTML page.但问题是 js 脚本需要一些时间才能加载到 HTML 页面上。 It works fine if I add a sleep for few seconds in my java code and then execute the js function.如果我在我的 java 代码中添加睡眠几秒钟,然后执行 js function,它工作正常。

index.html索引.html

<!DOCTYPE HTML>
<html lang="en">
<head>
</head>
<body>

</body>
<script>
    var loadJS = function(url) {
        var script = document.createElement("script");  
        script.src = url;  
        document.body.appendChild(script); 
    }   
</script>
</html>

Java Code Java代码

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("www.test-url.com");
js.executeScript("loadData(123)");

The above code works if I add Thread.sleep(5000);如果我添加Thread.sleep(5000);上面的代码有效between the above js.executeScript code lines but not when I remove it.在上面的 js.executeScript 代码行之间,但在我删除它时没有。 How do I replace the Thread.sleep(5000);如何替换Thread.sleep(5000); and still make it work并且仍然让它工作

Have you tried this out?你试过这个吗?

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("console.log('Javascript console');");

You need to cast a WebDriver into a JavascriptExecutor object.您需要将 WebDriver 转换为 JavascriptExecutor object。 ExecuteScript functions will not be available unless you perform this cast.除非您执行此转换,否则 ExecuteScript 函数将不可用。 Then you will have access to the.executeScript() function然后您将可以访问 .executeScript() function

Sample driver = new Sample (new SampleProfile());
driver.executeScript("console.log('Javascript console');");

Try out using this code before you execute your javascript, This will force the WebDriver to wait till the page is fully loaded:在执行 javascript 之前尝试使用此代码,这将强制 WebDriver 等待页面完全加载:

WebDriverWait wait = new WebDriverWait(driver, 50);
wait.until((ExpectedCondition<Boolean>) wd -> ((JavascriptExecutor) wd).executeScript("return document.readyState").equals("complete")); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM