在Selenium WebDriver中访问window.external函数

时间:2015-11-27 14:44:31

标签: javascript selenium selenium-webdriver

我想通过Selenium验证在页面上单击某个项目时是否正在调用外部javascript函数。 (我们已经有间谍进行茉莉花单元测试了。)

所以我的想法是拥有像

这样的东西
[InvalidArgumentException]                               
There are no commands defined in the "setup" namespace.

此代码的问题是我在第一行收到异常。

这是一个例外:

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;");

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

1 个答案:

答案 0 :(得分:1)

原来这是由于没有初始化window.called和window.external。对于那些希望做类似的事情的人,可以解决它。

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