Programming (back-end)

WebBrowser.InvokeScript case study – running custom JavaScript

Last time I played with WebBrowser control (in WindowsPhone) as I wanted to automate navigation in some external web application. The first thought was to use InvokeScript method as it allows to run custom script. But the thing was not so obvious, that’s why I’d like to share my study here. Let’s start with a simple code snippet (WebBrowser is an instance of WebBrowser control):


This code will throw System.SystemException: An unknows error has occurred. Error: 80020006. It appears that InvokeScript method can execute only functions that already exist. Weird, especially if you played with ExecuteScript in Selenium. So what, am I not able to execute my own code? Hopefully there is Javascript eval function:


OK, now it’s better. Alert appeared. Let’s try to do something more than a single expression:


Whew! Another success. What about returning values?  Failed! It returned empty string. Why not 2? Why empty string and not null? InvokeScript return type is object. Maybe I missed “return” keyword. Let’s check:


Now there is: System.SystemException: An unknows error has occurred. Error: 80020101. After reading the Internet, I’ve found enigmatic: jQuery selector not working on Windows Phone 7. It seems that InvokeScript has problems with returning values from eval function. The solution here is to cast to string on JavaScript’s side


Unfortunately it’s more complicated when we have more JavaScript to run as it should always cast to string:


My approach to solve it was to use self executing function encapsulating the custom script. For better use of it let’f extract a method:


Finally we have to remember about adding return keyword but that’s the price worth to pay.


One thought on “WebBrowser.InvokeScript case study – running custom JavaScript

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s