JavaScript, Uncategorized, windows phone

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):

script1

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:

script2

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

script3

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:

script5

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

script6

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

script7

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:

script8

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

Advertisements

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:

WordPress.com Logo

You are commenting using your WordPress.com 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