Google Windows Store Apps: How to load local html file in WebView control, beginners tutorials (C#-XAML) | SubramanyamRaju Xamarin & Windows App Dev Tutorials

Wednesday, 6 January 2016

Windows Store Apps: How to load local html file in WebView control, beginners tutorials (C#-XAML)

Introduction:

Some times we may need to load local html file in webview, and fortunately we can easily load html file in window phone (in both silverlight & winrt). However this article will explain how to load local html file in WinRT WebView control using different ways :)

Requirements:

  • 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. 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.

Description:

Previously in silverlight platfrom(WP8.0/WP8.1), we are using below code to load html content in WebBrowser control with different ways.
Silverlight WindowsPhone:

  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>");  
WinRT WindowsPhone:
Now lets start to write code for load html content in WebView control with different ways.
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)
3. And lets add below code in MainPage.xaml, which is having one WebView control is for displaying html conent , and one Button is for loading html on Click event.

  1. <Grid  Background="LightBlue">  
  2.        <Grid x:Name="LayoutRoot" Margin="5">  
  3.            <Grid.RowDefinitions>  
  4.                <RowDefinition Height="Auto"/>  
  5.                <RowDefinition Height="Auto"/>  
  6.            </Grid.RowDefinitions>  
  7.            <WebView Name="WebBrowserName" Grid.Row="0" Height="272" Margin="5" />  
  8.            <Button Name="BtnLoadHtml" Foreground="Black" Grid.Row="1" HorizontalAlignment="Stretch" Content="Load local html file" Click="BtnLoadHtml_Click" />  
  9.        </Grid>  
  10.    </Grid>  
4. In general, in WinRT we have following ways to load html content in WebView control
  1. private void BtnLoadHtml_Click(object sender, RoutedEventArgs e)  
  2.        {  
  3.   
  4.            //Load local file using 'Source' property  
  5.            WebBrowserName.Source = new Uri("ms-appx-web:///HTMLPage.html");  
  6.   
  7.            //Load local file using 'Navigate' method  
  8.            WebBrowserName.Navigate(new Uri("ms-appx-web:///HTMLPage.html"));  
  9.   
  10.            //Load html string using 'NavigateToString' method  
  11.            WebBrowserName.NavigateToString("<Html><Body><h1>Load local html string in windows phone winrt app.<h1><Body></Html>");  
  12.        }  

Note: in WinRT WebView can load content from the application’s package using ms-appx-web://, from the network using http/https, or from a string using NavigateToString. It cannot load content from the application’s data storage. To access the intranet, the corresponding capability must be turned on in the application manifest.

5. And also we have another way to load local html file in WinRT WebView control is using NavigateToLocalStreamUri we can load local web content of application. This method can be used in both windows store(8.1) and windows phone 8.1 [Windows Runtime apps only].

5.1 How to load local html file in WebView control using NavigateToLocalStreamUri:

5.1.1 Why NavigateToLocalStreamUri method?
We can also use NavigateToString to navigate to static HTML content, but does not provide a way to generate these resources programmatically.(Ex: we can't load local html files with NavigateToString method). So we can handle it from NavigateToLocalStreamUri  method.

Okay lets follow below steps to use NavigateToLocalStreamUri  
Step 1:
Right click on project , create Html page 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 LoadSearch(searchString) {  
  6.         window.location = "http://www.bing.com/search?q=" + searchString  
  7.         window.external.notify("Search completed")  
  8.      }  
  9.     </script>  
  10. </head>  
  11. <body>  
  12.     <h1 style="color:red;">Load local html file in windows phone winrt app.</h1>  
  13. </body>  
  14. </html>  


and project reference folder should be like below:
Step 2:
Right click on project and create helper class name is 'StreamUriWinRTResolver' and it should implement 'IUriToStreamResolver' interface that translates a URI pattern into a content stream.
  1. public sealed class StreamUriWinRTResolver : IUriToStreamResolver  
  2.     {  
  3.         public IAsyncOperation<IInputStream> UriToStreamAsync(Uri uri)  
  4.         {  
  5.             if (uri == null)  
  6.             {  
  7.                 throw new Exception();  
  8.             }  
  9.             string path = uri.AbsolutePath;  
  10.   
  11.             // Because of the signature of the this method, it can't use await, so we   
  12.             // call into a seperate helper method that can use the C# await pattern.  
  13.             return GetContent(path).AsAsyncOperation();  
  14.         }  
  15.   
  16.         private async Task<IInputStream> GetContent(string path)  
  17.         {  
  18.             // We use a package folder as the source, but the same principle should apply  
  19.             // when supplying content from other locations  
  20.             try  
  21.             {  
  22.                 Uri localUri = new Uri("ms-appx://" + path);  
  23.                 StorageFile f = await StorageFile.GetFileFromApplicationUriAsync(localUri);  
  24.                 IRandomAccessStream stream = await f.OpenAsync(FileAccessMode.Read);  
  25.                 return stream;  
  26.             }  
  27.             catch (Exception) { throw new Exception("Invalid path"); }  
  28.         }  
  29.     }  
Step 3:
On Button click event, use above helper class like below:
  1. private void BtnLoadHtml_Click(object sender, RoutedEventArgs e)  
  2.         {  
  3.             //Load local file using 'NavigateToLocalStreamUri' method  
  4.             Uri url = WebBrowserName.BuildLocalStreamUri("MyTag""HTMLPage.html");  
  5.             StreamUriWinRTResolver myResolver = new StreamUriWinRTResolver();  
  6.   
  7.             // Pass the resolver object to the navigate call.  
  8.             WebBrowserName.NavigateToLocalStreamUri(url, myResolver);  
  9.         }  
6. Output:

Important Notes:
1. In this article, we learn about new method called 'NavigateToLocalStreamUri' and your helper class should implement a interface called 'IUriToStreamResolver'.
2. Local html file path should be prefix with 'ms-appx-web://' (Ex:ms-appx-web://LoclalHtmlPage.html)
3. WebView control in windows phone WinRT is used for displaying html content, and in silverlight windows phone we called it as 'WebBrowser' control.
4. This sample will be work on all above windows phone 8.0 OS devices. 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. There is no store app in my Visual studio??? How can I fix this??

    ReplyDelete

Search Engine Submission - AddMe