Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 702
Ryan Avatar asked Dec 13 '12 10:12

Ryan


People also ask

What is executeScript()?

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.

What is JavascriptExecutor and when it will be used?

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.

Which of the following options in Selenium is used to click on an element through JavascriptExecutor?

In Selenium Webdriver, we can just use element. click() method to click on any element.

Why JavascriptExecutor is used in Selenium?

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.


1 Answers

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.

like image 198
Valentin Avatar answered Oct 21 '22 13:10

Valentin