Selenium and asynchronous JavaScript calls

后端 未结 2 2019
栀梦
栀梦 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:34

    For asynchronous code you have to use executeAsyncScript:

    JavascriptExecutor js = (JavascriptExecutor) driver; 
    String docInfoVal = (String) js.executeAsyncScript("" +
            "var done = arguments[0]; " +
            "getCurrentDocumentInfo(\"somestuff\"," +
                "function(docId) {" +
                    "done(docId);" +
                "}" +
            ");");
    

    The script you call with executeAsyncScript will have a callback added to the list of arguments passed to it. Since you pass no arguments to your script, then arguments[0] contains the callback. Your code must call this callback when it is done working. The value you give to the callback is the value that executeAsyncScript returns.

    In the code above, I've spelled out the call to done by putting it in an anonymous function but the code could be written more concisely as:

    JavascriptExecutor js = (JavascriptExecutor) driver; 
    String docInfoVal = (String) js.executeAsyncScript("" +
            "var done = arguments[0]; " +
            "getCurrentDocumentInfo(\"somestuff\", done);");
    

    Or even:

    JavascriptExecutor js = (JavascriptExecutor) driver; 
    String docInfoVal = (String) js.executeAsyncScript(
            "getCurrentDocumentInfo('somestuff', arguments[0]);");
    

提交回复
热议问题