Jaime Rodriguez On Windows Phone, Windows Presentation Foundation, Silverlight and Windows 7
Two people asked on this post about communication between HTML and Silverlight, so I thought I would share broadly about the more 'advanced' techniques. [Don't be misled, advanced is still easy, just explaining all you can do].
Silverlight on Windows Phone allows you to host HTML content in a WebBrowser control. You get bi-directional communication between the control and the HTML content:
If you own the HTML page you are hosting, the infrastructure above is all you need to get anything done (since you can just add the javascript to communicate). If you don’t own the page you are calling things are slightly more interesting but still very doable – these are the scenarios that fuel this post –. These are the communication mechanisms I use when talking to HTML on a page that comes from a server that I can’t control or influence.
webBrowser.InvokeScript("execScript", "history.go(-1)");
// this will fail, it returns null // object height = webBrowser.InvokeScript ( "eval", "document.body.offsetHeight" ); // this works string height = (string) webBrowser.InvokeScript ( "eval", "document.body.offsetHeight.toString()" );
StringBuilder bldr = new StringBuilder(); bldr.Append("var script = document.createElement('script');"); bldr.Append("script.text = 'function cb () { "); bldr.Append("window.external.notify (\"this text was injected on the fly\");}';"); bldr.Append("var headNode = document.getElementsByTagName('HEAD'); "); bldr.Append( "if (headNode[0] != null);headNode[0].appendChild(script); ;"); bldr.Append("var element= document.getElementById('btn'); "); bldr.Append("if ( element != null ) element.onclick = cb;"); webBrowser.InvokeScript("execScript", bldr.ToString());
I am sure there are more techniques, but the combination of the 3 above has gotten me pretty far in communicating between JS and Silverlight. If you want to see the code above in action, download this sample.
Happy Windows Phone coding!
If you want to keep up with Windows Phone on a more frequent basis, subscribe to my Windows Phone question of the day RSS feed.