0

Is it possible to modify the value of a Java variable from within Selenium JavascriptExecutor?

I know it is possible to access Java variables inside JavascriptExecutor as '"+myjavavar+"' but how do we modify it?

If I use '"+myjavavar+"'= somenewvalue; it fails with error "invalid assignment left-hand side".

4
  • 1
    You are probably confusing java and javascript here. You want to modify a javascript variable through JavascriptExecutor, right? Commented May 14, 2015 at 11:28
  • @alecxe No, I want to access and modify a java variable through JavascriptExecutor. Commented May 14, 2015 at 11:33
  • 4
    Could you add more details about the motivation behind this kind of requirement? Commented May 14, 2015 at 11:34
  • Basically what I am looking to achieve here is either (1) OR (2) of below. (1) As my JavascriptExecutor modifies some javascript variables, I need that values to be available within the java program. A kind of global javascript variable which can be used within both java and javascript. (2) I have a java variable which has some initial value. I need to pass this value to JavascriptExecutor and within the JavascriptExecutor I will update this value on some conditions and then continue the java program with the new value. I don't want to use any cookies based global storage here. Commented May 14, 2015 at 11:58

1 Answer 1

4

You can both get and set javascript variables through JavascriptExecutor. To have a "global" variable during your test session available in every script you execute, keep it on the global window object. Example:

JavascriptExecutor js = (JavascriptExecutor) driver;

// set the value (note how the arguments are passed into)
js.executeScript("window.myvar = arguments[0];", "Test");

// get the value (note the "return")
String myvar = (String) js.executeScript("return window.myvar;");
System.out.println(myvar);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks...! Fair enough.

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.