Load local html file in WebView Metro Style app

前端 未结 3 1060
独厮守ぢ
独厮守ぢ 2021-01-11 17:57

I\'m having a bit of trouble loading an html file in a WebView control in a metro style app. I\'ve been searching the internet and found out that you can\'t load a local htm

相关标签:
3条回答
  • You can switch contexts by using the ms-appx-web:/// protocol instead of ms-appx:///, which I've had successfully loading local Html files and associated CSS and JavaScript, within a HTML/JS Metro Style App.

    I've not tried this in a XAML Metro Style App, but believe that the ms-appx-web:/// protocol can be used. The limitation is that your Html (if local i.e not web hosted) has to reside within a WinRT package, which it appears to in your case i.e. /Assets.

    0 讨论(0)
  • 2021-01-11 18:35

    I ran into the same problem. In my application I have a file called Default.html which is read and it's contents are displayed in a WebView control.

    var html = await Windows.Storage.PathIO.ReadTextAsync("ms-appx:///Assets/Default.html");
    MyWebView.NavigateToString(html);
    

    Note that I'm using await and ReadTextAsync so that the code is asynchronous (as one should when doing IO), the function you place this snipped it must be defined as async, example:

    private async void LoadWebView( file ) { ... }
    
    0 讨论(0)
  • 2021-01-11 18:36

    Here is a quick sample tell me if this help you:

    I have an Html file in my Assets folder called MyHTMLPage, it has a build action of type content and a Copy to Output to Copy Always. My Html file:

    <!DOCTYPE html>
    
    <html lang="en" xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
    <div style="background-color: chartreuse">HELLO WORLD, from a webview</div>  
    </body>
    </html>
    

    On my Main Page.xaml:

     <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
            <WebView x:Name="MyWebView"  Width="200" Height="300"></WebView>
        </Grid>
    

    On my Main Page.cs:

     public sealed partial class MainPage : Page
        {
            public MainPage()
            {
                this.InitializeComponent();
                Loaded += MainPage_Loaded;
            }
    
            private void MainPage_Loaded(object sender, RoutedEventArgs e)
            {
                string src = "ms-appx-web:///Assets/MyHTMLPage.html";
                this.MyWebView.Navigate(new Uri(src));
            }
        }
    

    and Voila this should work.

    0 讨论(0)
提交回复
热议问题