【问题标题】:Unable to access global variable through FirefoxDriver无法通过 FirefoxDriver 访问全局变量
【发布时间】:2017-01-17 09:28:04
【问题描述】:

我正在尝试检索 JavaScript 全局变量的值,当我在 FireFox 中运行测试时总是得到 undefined

此测试在 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+"|");

当我运行它时,strnull 并且在浏览器的 JavaScript 控制台中 window.seleniumTesting 被记录为 undefined

如果我使用ChromeDriver 而不是FirefoxDriver。一切都按预期进行(strJust A Test 和控制台日志:Just A Test)。

这似乎是一个 JavaScript 上下文问题。似乎在 FirefoxDrive 中,JavaScript 上下文不是网页的上下文。

这是一个已知问题吗?我可以将驱动程序的 JavaScript 上下文更改为网页的上下文吗?

[编辑] 我在 OSX 上使用geckodriver

[编辑] 和 FireFox 版本 47。

【问题讨论】:

  • 你确定你得到nullFirefoxDriver 因为它在我的情况下在两个浏览器上都可以正常工作..:)
  • @SaurabhGaur 是的,我确定。这可能是由我正在使用的gecko 驱动程序引起的。它可能不适用于我当前的 FireFox 版本。
  • 我正在使用当前版本的 Firefox 和 geckodriver 进行尝试,在我的情况下它运行良好。你为什么用Thread.currentThread().wait(55000);??将executeAsyncScript() 用作(String)((JavascriptExecutor) browser).executeAsyncScript("callback = arguments[0]; callback(window.seleniumTesting);"); 的更好方法。可能有帮助..:)
  • @SaurabhGaur 我刚刚尝试了executeAsyncScript(...),得到了相同的结果。我正在使用wait(...) 调用来确保页面已完全加载。
  • 您能分享一下如何用geckodriver 初始化FireFoxDriver,因为我使用MarionetteDriver 而不是在Firefox 上对其进行测试..

标签: javascript java selenium webdriver


【解决方案1】:

使用geckodriver 当前为v0.10.0,您必须使用window.wrappedJSObject 访问窗口对象的非标准属性:

String str = (String)((JavascriptExecutor)driver).executeScript("return window.wrappedJSObject.seleniumTesting;");

【讨论】:

  • 非常感谢这个,也感谢@SaurabhGaur。你怎么知道window.wrappedJSObject 是否在某些文档中提到过?
  • @Titus,在木偶驱动的文档中有提到,它是壁虎驱动的下一层。
  • 好的,再次感谢。我会调查的,这一切我才刚刚开始。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-01-17
  • 2014-04-08
  • 1970-01-01
  • 2014-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多