I am using the method executeScript
in selenium web driver, I found a problem:
js.executeScript("var b='1'; ");
js.executeScript("alert(b)");
After I run above code, I suppose get a alert window with value is 1
, but it says:
b is not defined
My question is: I defined b
as a global variable, but why I cannot get it in later?
The executeScript command executes a snippet of JavaScript in the context of the currently selected frame or window. The script fragment will be executed as the body of an anonymous function. To store the return value, use the 'return' keyword and provide a variable name in the value input field.
JavaScriptExecutor is an interface that is used to execute JavaScriprt through selenium webdriver. JavaScript is a programming language that interacts with HTML in a browser, and to use this function in Selenium, JavascriptExecutor is required. JavascriptExecutor Provides Two Methods: ExecuteScript. ExecuteAsyncScript.
In Selenium Webdriver, we can just use element. click() method to click on any element.
Javascript Executor is a Selenium Interface which directly lets you Interact with HTML DOM of the webpage. JavascriptExecutor provides a way to automate a user interaction even when page is not essentially loaded completely or elements are placed in a way that the direct interaction is blocked.
Defining a variable as
var b='1'
limits the scope to the execution of the script. Selenium wraps the execution of javascript snippets into their own script so your variable does not survive the end of the script. Try
window.b = '1';
and then later
alert(window.b);
to put the variable into global scope.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With