Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to access global variable through FirefoxDriver

I'm trying to retrieve a JavaScript global variable's value and I always get undefined when I run the test in FireFox.

This test is successful in Chrome.

index.html

<html>
<head>
<script type="text/javascript">
   window.seleniumTesting = "Just A Test";
</script>
</head>
<body>
    ....
</body>
</html>

Test.java

WebDriver drive = new FirefoxDriver();
driver.get("http://localhost");
// Wait for the page to load. I know there are better ways of doing this.
synchronized (Thread.currentThread()) {
    try {
        Thread.currentThread().wait(55000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
String str = (String)((JavascriptExecutor) driver).executeScript("console.info(window.seleniumTesting); return window.seleniumTesting;");
System.out.println("str: |"+str+"|");

When I run this, str is null and in the browser's JavaScript console window.seleniumTesting is logged as undefined.

If I use a ChromeDriver instead of FirefoxDriver. Everything is as expected (str is Just A Test and the console logs: Just A Test).

This seems to be a JavaScript context problem. It seems that in FirefoxDrive the JavaScript context is not the web page's context.

Is this a known issue ? Can I change the driver's JavaScript context to the web page's context ?

[EDIT] I'm using the geckodriver for OSX.

[EDIT] And FireFox version 47.

like image 649
Titus Avatar asked Dec 05 '25 21:12

Titus


1 Answers

With the geckodriver currently v0.10.0, you must use window.wrappedJSObject to access a non-standard property of the window object:

String str = (String)((JavascriptExecutor)driver).executeScript("return window.wrappedJSObject.seleniumTesting;");
like image 122
Florent B. Avatar answered Dec 08 '25 11:12

Florent B.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!