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?

2

1 Answer 1

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:

Sign up to request clarification or add additional context in comments.

2 Comments

@alecxe So, window.test = false; registers test variable against current driver?
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.