The executeScript method (selenium web driver) cannot determine a global variable for later use?

I use the executeScript method in the selenium web driver, I found a problem:

 js.executeScript("var b='1'; "); js.executeScript("alert(b)"); 

After running on the code, I expect to get a warning window with a value of 1 , but it says:

 b is not defined 

My question is: I defined b as a global variable, but why can't I get it later?

+4
source share
1 answer

Defining a variable as

 var b='1' 

limits the scope of the script. Selenium completes the execution of javascript fragments in its own script, so your variable will not be saved at the end of the script. Try

 window.b = '1'; 

and then later

 alert(window.b); 

to put the variable in the global scope.

+7
source

All Articles