Home > Back-end >  geckodriver - cannot create a js variable then read it?
geckodriver - cannot create a js variable then read it?

Time:10-07

I'm using geckodriver.exe for some Selenium automation with Firefox. There are times when I need to make a global variable using ExecuteScript, then read that variable later on:

driver.ExecuteScript("  x = 'test'; ");
var result = driver.ExecuteScript("  return x; ");

In ChromeDriver I get a result back and it is "test" as expected.

With GeckoDriver I get null on that second call. Is there something I am doing wrong? I really do intend to create a global variable here!

CodePudding user response:

It does seem a little odd that your solution didn't work. Your can leverage a quirk with Javascript where setting a property on a window object creates an implicitly declared global variable:

var js = (IJavaScriptExecutor)driver;

js.ExecuteScript("window.x = 'test';");

When dealing with a <frameset> or <iframe> you can reference top to set a global variable in the top level window object:

js.ExecuteScript("top.x = 'test';");

My guess is the code you tried was setting a global variable, just not on the window object you thought.

  • Related