javascript - 访问 Selenium WebDriver 中的 window.external 函数

标签 javascript selenium selenium-webdriver

我想验证当单击页面上的某个项目时,是否通过 Selenium 调用外部 javascript 函数。 (我们已经有了 Jasmine 单元测试,用 spy 覆盖了这一点)。

所以我们的想法是拥有类似的东西

WebDriver.ExecuteJavascript<string>("window.called = false");
WebDriver.ExecuteJavascript<string>("window.external.MyFunction = function(){ window.called = true; }");
var element = WebDriver.GetElement(By.ClassName("awesomeElement"));
element.Click();

string value = WebDrider.ExecuteJavascript<string>("return window.called;");

这段代码的问题是我在第一行遇到异常。

这是异常(exception):

Exception: System.NullReferenceException: Object reference not set to an instance of an object.
   at System.Object.GetType()
   at OpenQA.Selenium.Support.Extensions.WebDriverExtensions.ExecuteJavaScript[T](IWebDriver driver, String script, Object[] args)

请注意,WebDriver 不为 null,并且该方法正在抛出异常。我找不到任何文件说访问窗口函数/变量受到限制。有什么想法可能是错误的吗?

最佳答案

事实证明,这是由于未初始化 window.called 和 window.external 造成的。对于那些想要做类似事情的人来说,下面的代码片段可以解决这个问题。

IJavaScriptExecutor executor = WebDriver as IJavaScriptExecutor;
executor.ExecuteScript("window.called='false';");
executor.ExecuteScript("window.external={};");
executor.ExecuteScript("window.external.MyFunction=function()..;");

关于javascript - 访问 Selenium WebDriver 中的 window.external 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33959805/

相关文章:

javascript - 以整小时增量创建选择列表

javascript - 如何捕获CSS样式的onload事件?

java - 如何在java代码中获取cucumber中具有多个管道的步骤的参数?

selenium - Selenium 可以与现有的浏览器 session 交互吗?

python - 元素当前不可见,可能无法操作 - Selenium webdriver

java - Java Selenium 中的正则表达式

android - 使用 Selenium 在 Kobiton 设备上滑动

javascript - 如何使用javascript多次访问一个页面?

javascript - 使用 AngularJS 和 PHP 发送电子邮件

python - Selenium 中的图像映射点击