Google Silverlight WindowsPhone : 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

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

Introduction:

We can use WebBrowser control in silverlight windows phone(8.0 &8.1) for displaying html content, and so some times we may need to communicate windows phone native code (C#) from webbrowser html content.
For example, lets assume there is one html button in webbrowser content, and when clicking on html button we need to navigate to another windows phone native page. Which means we need to trigger windowsphone native program(i.e, C# code) from javascript function and then navigate to another page.

Also from this article we can learn how to call javascript function from windows phone C# code.

Requirements:

  • This sample is targeted for windows phone silverlight 8.0 OS,So make sure you’ve downloaded and installed the Windows Phone 8.0 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 2012 for Windows or Later.

Description:

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

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.             <phone:WebBrowser  x:Name="WebBrowserName" Height="400" IsScriptEnabled="True" Margin="5" />  
  4.             <Button x:Name="Button1" Content="Call javascript function from c#" Click="Button1_Click" />  
  5.         </StackPanel>  
  6.     </Grid>  
Note: Don't forgot to set WebBrowser property to IsScriptEnabled="True", otherwise ScriptNotify event will not be fire forever :P

Step 3: Create Html page in project (Ex:LocalHTMLPage.html) and add your html content in it.
Example html content:
  1. <html xmlns="http://www.w3.org/1999/xhtml">  
  2. <head>  
  3.     <title></title>  
  4.     <script type="text/javascript">  
  5.         function JavaScriptFunctionName() {  
  6.             alert("Calling from C# code.");  
  7.         //window.external.notify("SomeSpecificFunctionCall()");  
  8.      }  
  9.     </script>  
  10. </head>  
  11. <body>  
  12.     <h1 style="color:red;font-size:35px;">Communication BTW JavaScript & C# in windows phone silverlight app.</h1>  
  13.     <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')" />  
  14. </body>  
  15. </html> 
and project reference folder should be like below:

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

  1. //Load local html file using 'Source' property  
  2. WebBrowserName.Source = new Uri("LocalHTMLPage.html", UriKind.Relative);  
  3.   
  4. //Load local html file using 'Navigate' method  
  5. WebBrowserName.Navigate(new Uri("LocalHTMLPage.html", UriKind.Relative));  
  6.   
  7. //Load html string using 'NavigateToString' method  
  8.  WebBrowserName.NavigateToString("<Html><Body><h1>Load local html string in windows phone silverlight app.<h1><Body></Html>");  
However in constructor, we need to load html content in WebBrowser before we need to register it for ScriptNotify event like below:
  1. public MainPage()  
  2.        {  
  3.            InitializeComponent();  
  4.   
  5.            //load local html file in webbrowser control  
  6.            WebBrowserName.Navigate(new Uri("LocalHTMLPage.html", UriKind.Relative));  
  7.   
  8.            //Regester webbrowser control for script notify event  
  9.            WebBrowserName.ScriptNotify += WebBrowserName_ScriptNotify;  
  10.        }  

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. void WebBrowserName_ScriptNotify(object sender, NotifyEventArgs e)  
  2.         {  
  3.             //This one will trigger when javascript function is invoked from html button click  
  4.             if (e.Value.StartsWith("CsharpFunctionName"))  
  5.             {  
  6.                // MessageBox.Show("called from javascript");  
  7.                 //Navigating to next page  
  8.                NavigationService.Navigate(new Uri("/NextWindowsPage.xaml",UriKind.Relative));  
  9.             }    
  10.         }  
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 void Button1_Click(object sender, RoutedEventArgs e)  
  2.   {  
  3.        WebBrowserName.InvokeScript("JavaScriptFunctionName");  
  4.    } 
6. Output:

Important Notes:
1. Don't forgot to set WebBrowser property to IsScriptEnabled="True", otherwise ScriptNotify event will not be fire forever :P
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.
WindowsWebBrowser
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  :)

1 comment:

  1. The first one is such an incredible picture. I love how it is just black, white and red, it leaves such an amazing effect.
    application development

    ReplyDelete

Search Engine Submission - AddMe