Detailed explanation of Selenium JavascriptExecutor

Selenium IDE practical series of video courses  http://edu.51cto.com/course/12954.html

Click the link to join the group [Joy Sharing Test Alliance]: https://jq.qq.com/?_wv=1027&k=5DiePik

    

    introduce

        In Selenium IDE, we can use the runScript command to execute js code snippets to assist in completing some tasks that Selenium is inconvenient to achieve. Similarly, in WebDriver, we can also use the JavascriptExecutor tool class to complete js code execution. I will detail the four points below. Explain how the tool is used and how it works.

        

    Topics discussed in this article include:

        1. JavascriptExecutor introduces two methods for executing js code.

        2. JavascriptExecutor uses examples of two methods to execute js code.

        3. The principle of JavascriptExecutor executing js.

        4. Common cases of JavascriptExecutor.


    Below we will explain the above three topics in detail!

    

    1. Introduction of two methods for JavascriptExecutor to execute js code

        Object executeScript(String script, Object... args);

        Object executeAsyncScript(String script, Object... args);

        

        The executeScript method takes two parameters and a return value:

        script , javascript code fragment, this js code fragment is the complete method body of the js function, and the return statement can be used as the return value of the function.

        args , parameter array, the parameter array is used to pass external data to the script (js code fragment), the parameters in the args array can be indexed by the arguments[index] method in the script; the parameter data type must be the following (number, boolean, String, WebElement, or List collection of the above data types), of course, no parameters can be left empty.

        Return value . The return value is calculated by the js code fragment and returned by the return statement. The data type of the return value can be (WebElement, Double, Long, Boolean, String, List or Map). There is no return statement, and the returned data here is null.

        

        The executeAsyncScript method takes two parameters and a return value:

        script , a javascript code fragment, this js code fragment is a complete method body of a js function, which is different from executeScript in two main points:

            1. The script here must explicitly call the callback method at the end of the code to notify the webdriver that the script execution ends; the callback method is the last element injected into the arguments array by the webdriver; it can be obtained by arguments[arguments.length-1] , and you can use the callback function to return the calculation result (you only need to put the return result as the parameter of the callback function)

            2. The script execution will have a timeout period, the default is 60s. If the callback method is not called within the timeout period, the JavascriptExecutor will throw a Timeout exception.

        args , the rules are the same as executeScript.

        Return value , the same rules as executeScript


    2. JavascriptExecutor uses examples of two methods to execute js code.

		//Example 1 Use the executeScript method to get the parameter array passed in the method in the js code
		//Use the parameter array passed in the arguments index method, and use return to return the result of the defined function body calculation.
		//Three parameters are passed in the code, the second and third parameters are indexed in the js statement.
		
		JavascriptExecutor jsExec = (JavascriptExecutor)driver;
		String functionBody = "return arguments[1]+','+arguments[2]";
		String returnRes = (String)jsExec.executeScript(functionBody, 1, "hello", "selenium");
		System.out.println(returnRes);
		
		
		//Example 2 Use the executeAsyncScript method to obtain the parameter array passed in by the method in the js code, and return the calculation result of the function body by calling the callback method
		//Three parameters are passed in the code, the second and third parameters are indexed in the js statement.
		
		//The timeout period is set for the callback method call. If the callback method is not called within the timeout period, it will wait for the set timeout period by default. If it does not return here, an exception will be thrown.
	        driver.manage().timeouts().setScriptTimeout(2, TimeUnit.SECONDS);
		
		String script = "var res = arguments[0] + ',' + arguments[1]; "
				+ "var callback = arguments[2];"
				+ "callback()";
		String returnVal = (String)driver.executeAsyncScript(script, "hello" , "selenium");
		System.out.println(">>>" + returnVal);

        3. The principle of JavascriptExecutor executing js.


        How to understand how JavascriptExecutor runs js code requires a certain understanding of the basics of javascript. First, we will list two examples of three definitions and calling functions in javascript. After reading the examples, it is not difficult for you to understand how webdriver runs javascript code. , but also to eliminate the confusion (why use arguments in javascript to receive the parameters passed in by the method).

    The first function definition method:
    function sum(a, b) {
        return a+b;
    }
    sum(2,3); //output 5
    
    The second function definition method:
    
    var sum = new Function('a', 'b', 'return a+b;');
    sum(2,3) //output 5
    
    The second way we can rewrite it as: 
    
    new Function('a', 'b', 'return arguments[0]+arguments[1]').apply(null,[1,2]);  //输出5

        Of course, the definition of functions is not limited to the above three ways of writing. We will focus on the second and third methods here. I believe that when you see these two ways of use, you already understand how webdriver calls js code, but you still have doubts. Why use arguments to receive parameters.

        All the functions we define are essentially the implementation of the Function class, and arguments are used as local variables in the definition of the Functions class, and all parameters are received through the arguments index, even if the parameters are not specified in the method definition, let's take a look at the following code example:


    function add(a) {
        var sum = 0,
        len = arguments.length;
        for (var i = 0; i <len; i ++) {
            sum += arguments[i];
        }
        return sum;
    }
    
    add(1,2,3,4);   //10

        

        I believe that everyone here should be very clear about how webdriver executes js code. In fact, webdriver defines anonymous functions to run javascript code through new Function.



Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326629962&siteId=291194637
Recommended