【发布时间】: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+"|");
当我运行它时,str 是 null 并且在浏览器的 JavaScript 控制台中 window.seleniumTesting 被记录为 undefined。
如果我使用ChromeDriver 而不是FirefoxDriver。一切都按预期进行(str 是 Just A Test 和控制台日志:Just A Test)。
这似乎是一个 JavaScript 上下文问题。似乎在 FirefoxDrive 中,JavaScript 上下文不是网页的上下文。
这是一个已知问题吗?我可以将驱动程序的 JavaScript 上下文更改为网页的上下文吗?
[编辑]
我在 OSX 上使用geckodriver。
[编辑] 和 FireFox 版本 47。
【问题讨论】:
-
你确定你得到
null和FirefoxDriver因为它在我的情况下在两个浏览器上都可以正常工作..:) -
@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