Google Windows Store Apps : How to communicate with C# code from WebBrowser javascript and vice versa, beginners tutorials (C#-XAML) | SubramanyamRaju Xamarin & Windows App Dev Tutorials

Wednesday, 6 January 2016

Windows Store Apps : How to communicate with C# code from WebBrowser javascript and vice versa, beginners tutorials (C#-XAML)


In previous article I wrote an article about silverlight windows phone and which can explain you about 'Communication between C# code and WebBrowser html content'. In this article we can learn how to do same thing in WinRT windows phone platform


  • This sample is targeted for windows phone WinRT 8.1 OS,So make sure you’ve downloaded and installed the Windows Phone 8.1 SDK or later. For more information, see Get the SDK.
  • I assumes that you’re going to test your app on the Windows Phone emulator. If you want to test your app on a phone, you have to take some additional steps. For more info, see Register your Windows Phone device for development.
  • This post assumes you’re using Microsoft Visual Studio Express 2013 for Windows or Later.


Step 1:
1. Open Microsoft Visual Studio Express 2013 for Windows (or) later.
2. Create new windows phone WinRT project using the "Blank App" template available under Visual C# -> Store Apps -> Windows Phone Apps. (for example project name :WindwsCsharpvsJavascript)

Step 2: And lets add below code in MainPage.xaml, which is having one WebView control is for displaying html content , and one Button is for loading html on Click event.

  1. <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">  
  2.         <StackPanel x:Name="LayoutRoot" Background="LightBlue">  
  3.             <WebView  x:Name="WebBrowserName" Height="400" Margin="5" />  
  4.             <Button x:Name="Button1" Content="Call javascript function from c#" Click="Button1_Click" />  
  5.         </StackPanel>  
  6. </Grid> 

Note: In WInRT no need to set property IsScriptEnabled="True". Because for WebView control we don't have property like IsScriptEnabled. And by default ScriptNotify event will be fire when javascript function invoked by webview content.
Step 3: Create Html page in project (Ex:LocalHTMLPage.html) and add your html content in it.
Example html content:

  1. <html xmlns="">  
  2. <head>  
  3.     <title></title>  
  4.     <script type="text/javascript">  
  5.         function JavaScriptFunctionName() {  
  6.             window.external.notify('JavaScriptFunctionName');  
  7.         }  
  8.     </script>  
  9. </head>  
  10. <body>  
  11.     <h1 style="color:red;font-size:35px;">Communication BTW JavaScript & C# in windows phone WinRT app.</h1>  
  12.     <input id="Button1" type="button" style="width:100%;height:100px;font-size:50px;" value="Call C# function from Html Button" onclick="window.external.notify('CsharpFunctionName')" />  
  13. </body>  
  14. </html>  

and project reference folder should be like below:

Step 4: In general, in WinRT windows phone we have different ways to load html content in WebView control

  1.  //Load local file using 'Source' property  
  2.            WebBrowserName.Source = new Uri("ms-appx-web:///LocalHTMLPage.html");  
  4.            //Load local file using 'Navigate' method  
  5.            WebBrowserName.Navigate(new Uri("ms-appx-web:///LocalHTMLPage.html"));  
  7.            //Load html string using 'NavigateToString' method  
  8.            WebBrowserName.NavigateToString("<Html><Body><h1>Load local html string in windows phone winrt app.<h1><Body></Html>");  

However in constructor, we need to load html content in WebView before we need to register it for ScriptNotify event like below:

  1. public MainPage()  
  2.        {  
  3.            this.InitializeComponent();  
  4.            //Load local html file using 'Navigate' method    
  5.            WebBrowserName.Navigate(new Uri("ms-appx-web:///LocalHTMLPage.html"));  
  7.            //Regester webbrowser control for script notify event    
  8.            WebBrowserName.ScriptNotify += WebBrowserName_ScriptNotify;  
  9.        }  

Step 5:
Calling C# Code from Javascript :
In  SciptNotify event we can get parameter values, once specific function is calling from html button click. Lets see above html page,there I written window.external.notify('CsharpFunctionName') is for calling C# function from html button onclick event. and so we will get this value on ScriptNotify event. After that in IF condition we can do anything as per our requirement, here in this sample i am trying to navigate to another windows phone page. 

  1. async void WebBrowserName_ScriptNotify(object sender, NotifyEventArgs e)  
  2.         {  
  3.             if (e.Value.StartsWith("CsharpFunctionName"))  
  4.             {  
  5.                 Frame.Navigate(typeof(NextWindowsPage));//Calling C# function from javascript  
  6.             }  
  7.             else if (e.Value.StartsWith("JavaScriptFunctionName"))  
  8.             {  
  9.                 Windows.UI.Popups.MessageDialog dialog = new Windows.UI.Popups.MessageDialog("Calling javascript function from C#");  
  10.                 await dialog.ShowAsync(); //  
  11.             }  
  12.         }  

Calling Javascript Code from C#:
In our html page we have javascript function name is JavaScriptFunctionName  ,so if we want to call this javascript function from C#. We need to write below code on windows phone button click event.

  1. private async void Button1_Click(object sender, RoutedEventArgs e)  
  2.         {  
  3.             await WebBrowserName.InvokeScriptAsync("JavaScriptFunctionName"new string[] { "" });//Calling javascript function from C#  
  4.         } 
6. Output:

Important Notes:
1. We don't have IsScriptEnabled property in WinRT webview control, and by default webview can trigger ScriptNotify event when javascript function is invoked from it content. 
2. Just reminder is WebView control in windows phone WinRT is used for displaying html content, and in silverlight windows phone we called it as 'WebBrowser' control.
3. This sample will be work on windows phone 8.0 OS devices or later. and this sample was tested in Nokia Lumia 735 device & Microsoft 535.
FeedBack Note:
Please share your thoughts,what you think about this post,Is this post really helpful for you?I always welcome if you drop comments on this post and it would be impressive.

Follow me always at  
Have a nice day by  :)

No comments:

Post a Comment

Search Engine Submission - AddMe