How does WPF WebBrowser Control handle window.external.notify()?

Every now and then we get some really good questions that make us think.  This was one of those questions. Here was the original Tweet that was sent our way.

For those of you unfamiliar with the context of the question, it comes from a Silverlight point of view. The developer would like to see how the WPF WebBrowser handles the interop communication between a WebBrowser Control and WPF acting as the main container for the app. Silverlight handles the communications between the hosted content and the Silverlight control using the WebBrowser.ScriptNotify event..

The WPF WebBrowser control does something a little different. The WPF WebBrowser control uses the ObjectForScripting property. This property requires that the object have its ComVisibleAttribute set to True and you are good to go. Here is an example…

In your Xaml:

 <WebBrowser x:Name=”HtmlHost” ObjectForScripting=”HtmlInteropClass” />

In your code:

 [System.Runtime.InteropServices.ComVisibleAttribute(True)]

Public Class HtmlInteropClass

{

 Public void MyMethod(string SomeValue)

 {

  ((MainWindow)Application.Current.MainWindow).SomeTextBox.Text = SomeValue;

 }

}

In your JavaScript:

 <script type=”text/javaScript”>

 Function wpfAppMethod(inputValue) {

  Window.external.MyMethod(inputValue);

 }

</script>

One thing to note from the sample code above… Any ComVisibleAttribute that is set to True is available for use by window.external. This opens up many more opportunities to create better code that can fit your needs more precisely.

I’ve attached a sample project that will provide a good start. For more reading on the WPF WebBrowser Control, you can start here.

If you have any questions or comments, please let me know. Thanks!

WpfHostingWebOCHostingSL.zip