Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Selenium WebDriver JavascriptExecutor to manipulate one JS variable in separate scripts

I need to reach the following scenario:

1) Initializing JS var with JavascriptExecutor that will indicate if some operation is done.

2) Do some ordinary manipulation with the renderer page.

3) Verify the change to the var created in point (1).

For example:

jsc.executeScript("var test = false;");

Now, some manipulation is done. And then:

String testVal = jsc.executeScript("return test;").toString

I get the error:

org.openqa.selenium.WebDriverException: {"errorMessage":"Can't find variable: test","request":{"headers":{"Accept":"application/json, image/png","Connection":"Keep-Alive","Content-Length":"35","Content-Type":"application/json; charset=utf-8","Host":"localhost:14025"},"httpVersion":"1.1","method":"POST","post":"{\"args\":[],\"script\":\"return test;\"}","url":"/execute","urlParsed":{"anchor":"","query":"","file":"execute","directory":"/","path":"/execute","relative":"/execute","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/execute","queryKey":{},"chunks":["execute"]},"urlOriginal":"/session/7e2c8ab0-b781-11e4-8a54-6115c321d700/execute"}}

When i'm running them in the same execution, it works correctly.:

   String testVal = jsc.executeScript("var test = false; return test;").toString;

From JavascriptExecutor doc i found the explanation i needed:

Within the script, use document to refer to the current document. Note that local variables will not be available once the script has finished executing, though global variables will persist.

What is my alternative/workaround to this?

like image 827
Johnny Avatar asked Nov 27 '25 12:11

Johnny


1 Answers

Not sure what is the motivation behind it, but you can use a globally available window object:

jsc.executeScript("window.test = false;");
String testVal = jsc.executeScript("return window.test;").toString

It might also be a use case for executeAsyncSript(), see:

  • Understanding execute async script in Selenium
like image 185
alecxe Avatar answered Nov 30 '25 01:11

alecxe