Windows Store Apps: Invoke ScriptNotify Event When we Click a Button Inside a WebView

The purpose of this article is to show a solution to invoke the ScriptNotify event when we click a button from a web page hosted in a WebView.

Introduction

In Windows Store apps it is possible to use a WebView control to show web pages and sometimes we may need to intercept the action between the web page and the code behind of the XAML page, to do other tasks based on the action.

There are some changes from Windows 8.0 to Windows 8.1 related to the WebView control. These differences can be found here What's new in WebView in Windows 8.1 and there is an interesting sample: How to intercept JavaScript alert in WebView in universal Windows apps from OneCode Team. In this sample, we will see a solution for when we click a button from a web page hosted in a WebView.

Description

To start, we need to create a Windows Store App. We can select the Blank Template and then we need to create a basic HTML page with a button as in the following:

  1. <!--<span class="hiddenSpellError" pre="" data-mce-bogus="1"-->DOCTYPE html>  
  2. <button id="MyButton" type="button">Click here...</button>  
We then need to define a WebView in the MainPage.xaml, as in the following:
  1. <WebView Name="WebView"  
  2.    Margin="100"  
  3.    NavigationCompleted="WebView_OnNavigationCompleted"  
  4.    ScriptNotify="WebView_OnScriptNotify"  
  5.    Source="ms-appx-web:///HtmlPage.html" />  
And in the code behind, we need to define the NavigationCompleted event handler as in the following:
  1. private async void WebView_OnNavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)  
  2. {  
  3.    await WebView.InvokeScriptAsync("eval"new[]  
  4.    {  
  5.       "var signButton=document.getElementById(\"MyButton\");" +  
  6.       "if (signButton.addEventListener) {" +  
  7.       "signButton.addEventListener(\"click\", MyButtonClicked, false);" +  
  8.       "} else {" +  
  9.          "signButton.attachEvent('onclick', MyButtonClicked);" +  
  10.          "} " +  
  11.          "function MyButtonClicked(){" +  
  12.          " window.external.notify('%%' + location.href);"+  
  13.       "}"  
  14.    });  
  15. }  
Here we are injecting JavaScript code into the web page that will add the event click to the "MyButton" button defined in the HTML page. Each time the click event is fired the function "MyButtonClicked" will be called and it will fire the ScriptNotify event providing the URL.

Now we need to define the ScriptNotify event handler, as in the following:
  1. private void WebView_OnScriptNotify(object sender, NotifyEventArgs e)  
  2. {  
  3. var url = e.Value;  
  4. }  
When this event occurs we will get the value returned by the web page.

Running the Application



And by clicking the button we will get the URL value, as we can see in the following image.