Mavi Domates
Mavi Domates

Reputation: 4521

Accessing window.external functions in Selenium WebDriver

I want to verify an external javascript function is being called when an item is clicked on the page, via Selenium. (We already have jasmine unit tests covering this with spies).

So the idea is to have something like

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

The problem with this code is I'm getting an exception in the first line.

This is the 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)

Please note that WebDriver is not null, and the method is throwing. I couldn't find any documents saying that accessing to window functions / variables are restricted. Any ideas what might be wrong?

Upvotes: 0

Views: 1158

Answers (1)

Mavi Domates
Mavi Domates

Reputation: 4521

Turns out this was due to not initializing the window.called and window.external. For the folks who are looking to do something similar following snippet would solve it.

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

Upvotes: 1

Related Questions