0

I'm trying to execute a js function after js script gets loaded on an HTML page. But the issue is js script takes some time to load on the HTML page. It works fine if I add a sleep for few seconds in my java code and then execute the js function.

index.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

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

The above code works if I add Thread.sleep(5000); between the above js.executeScript code lines but not when I remove it. How do I replace the Thread.sleep(5000); and still make it work

1

2 Answers 2

2

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. ExecuteScript functions will not be available unless you perform this cast. Then you will have access to the .executeScript() function

Sample driver = new Sample (new SampleProfile()); driver.executeScript("console.log('Javascript console');"); 
2
  • Yes, I have done that and after I load the js using executeScript I want to execute a js function but the function is not found as the script has not been loaded on the HTML page yetCommentedMar 24, 2021 at 16:09
  • yeah, I am loading the js in the headerCommentedMar 24, 2021 at 16:40
1

Try out using this code before you execute your javascript, This will force the WebDriver to wait till the page is fully loaded:

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

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.