3

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?

Johnny
  • 14,397
  • 15
  • 77
  • 118
  • 1
    Upvote for an interesting question. – Saifur Feb 18 '15 at 16:01
  • possible duplicate of [The browser console doesn't recognize js vars that were injected with selenium webdriver](http://stackoverflow.com/questions/28457571/the-browser-console-doesnt-recognize-js-vars-that-were-injected-with-selenium-w) – Louis Feb 18 '15 at 17:23

1 Answers1

3

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:

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • 1
    @alecxe So, `window.test = false;` registers `test` variable against current `driver`? – Saifur Feb 18 '15 at 15:59
  • 1
    @Saifur I think it is in the "scope" of the current browser window - hence, basically, you can say that it in the scope of the current webdriver session. – alecxe Feb 18 '15 at 16:09