Execute C# Function in Windows 8 App From WebView Page

Jun 21, 2013


In last couple of blog posts we have been looking at the different use cases of WebView Control. In order to follow along with this post you should have basic understanding of WebView Control. If not, go through below posts to get the basic idea about this control.

  1. Working with the XAML WebView Control
  2. Invoking JavaScript Form Windows8 App Inside WebView Page

In this blog post we will take a look at following two scenarios.

  • How we can construct the dynamic HTML content and navigate our WebView control to that dynamically generated content.
  • how we can invoke a C# function inside our Windows 8 Application from JavaScript function.

For the first one we will be using the NavigateToString function from WebView control. And for invoking our C# function from JavaScript we will be using ScriptNotify function.

I am using the Project we built in previous blog post. You might want to quickly read through that to follow along with this post.

Constructing the Dynamic HTML in Windows 8 Application

We have added a new button, on the click event of that button we will navigate to the dynamic HTML we have constructed.

Adding button

Navigate To Dynamic html

Observe the NavigateToString function which loads that snippet of HTML into our WebView control.

NavigateToString

Notifying Windows 8 App From WebView Page

Let's examine the HTML snippet. It is a simple page with a button and a small JavaScript function. The JavaScript function uses window.external.notify method passing a parameter passed to it's wrapper function SayHi.

Next, Let's go ahead and setup our XAML application to listen to this event. For this, our MaingPage.xaml will subscribe to the NotifyScript event. Every time we click on the button inside our HTML page this function will be invoked.

Subscribing To The Event

Invoking The Button

This concludes three part series of blog posts on WebView control. The component has all the features we need to navigate to external web pages and back and forth communication between Windows 8 application and pages hosted in the component.