Search code examples
wpfwindows-community-toolkit

Why I cannot Navigate the html file by using WebView inside of the App in Wpf?


I make a Wpf projcect which demos how to use WebView to Navigate a html file inside of the App, but fails.

The main cs file code is below:

    public MainWindow()
    {
        this.InitializeComponent();

        this.wv.ScriptNotify += Wv_ScriptNotify;

        this.Loaded += MainPage_Loaded;
    }

    private async void Wv_ScriptNotify(object sender, Microsoft.Toolkit.Win32.UI.Controls.Interop.WinRT.WebViewControlScriptNotifyEventArgs e)
    {
        //await (new MessageDialog(e.Value)).ShowAsync();
        textBlock.Text = e.Value;

        //返回结果给html页面
        await this.wv.InvokeScriptAsync("recieve", new[] { "hehe, 我是个结果" });
    }

    private void MainPage_Loaded(object sender, RoutedEventArgs e)
    {
        //我们事先写好了一个本地html页面用来做测试
        this.wv.Source = new Uri("ms-appx-web://Assets/index.html");
        //this.wv.Source = new Uri("http://www.baidu.com");
    }

And the html file index.html is inside of the project, located at Assets/index.html. Its source code is here: https://github.com/tomxue/WebViewIssueInWpf/raw/master/WpfApp3/Assets/index.html

I put the project code onto GitHub: https://github.com/tomxue/WebViewIssueInWpf.git

If the project works well, when WebView visits the inner html file, it should show a button at first. But I saw nothing.

More:

According to the accepted answer(Thank to Pavel Anikhouski), I changed my code as below and it now works.

    private void MainPage_Loaded(object sender, RoutedEventArgs e)
    {
        //我们事先写好了一个本地html页面用来做测试
        //this.wv.Source = new Uri("ms-appx-web://Assets/index.html");
        //this.wv.Source = new Uri("http://www.baidu.com");

        var html = File.ReadAllText("../../Assets\\index.html");
        wv.NavigateToString(html);
    }

Solution

  • It seems to be a known issue with WebView control in WindowsCommunityToolkit

    • You can use only absolute URIs to resources in members of the WebView control that accept string paths.
    • WebView controls don't recognize the ms-appx:/// prefix, so they can't read from the package (if you've created a package for your application).
    • WebView controls don't recognize the File:// prefix. If you want to read a file into a WebView control, add code to your application that reads the content of the file. Then, serialize that content into a string, and call the NavigateToString(String) method of the WebView control.

    So, instead of loading a file this.wv.Source = new Uri("ms-appx-web://Assets/index.html"); try to read a local file and then navigate to the string

    var html = File.ReadAllText("Assets\\index.html");
    this.wv.NavigateToString(html);
    

    It should work fine (I've seen the button and message at my end). Also, don't forget to copy Assets\index.html to the output directory (set Copy Always or Copy if newer)