Unable to inject javascript using selenium 3 in firefox

795 views Asked by At

I am injecting java script variables using selenium and retrieving it for verification.

Below is my sample code, which was working fine with selenium version 2.53.1. When I upgraded to selenium 3 and started to use gecko driver for firefox, it throws exception when I am retrieving value.

driver.executeScript("globalVar='Amit';");
Object result = driver.executeScript("return globalVar");
System.out.println(result.toString());

Exception:

org.openqa.selenium.JavascriptException: ReferenceError: globalVar is not defined

In selenium 3 same code also working for Chrome.

Am I missing anything here? Or is there any capabilities added to allow such things in Firefox/Gecko driver?

1

There are 1 answers

0
alecxe On

The variables you set in a script that you execute are not global - they are "sitting" in the scope of the executed function. If you want to have a global variable that you want to access across multiple executed scripts, you have to use one of the available global objects, e.g. window:

driver.executeScript("window.globalVar = 'Amit';");
Object result = driver.executeScript("return window.globalVar");
System.out.println(result.toString());