7

I have a basic webpage that I am attempting to load into a WebView on a XAML page. The relevant code is such:

<WebView x:Name="WebViewQuestionText" Source="editor.html" HeightRequest="500" WidthRequest="500" />

As per the official Microsoft .NET MAUI documentation, I have editor.html located in /Resources/Raw/editor.html and set to a Build Action of MauiAsset. During runtime I don't generate any errors but the WebView is blank. An inspection of the WebView reveals a webpage that is barebones with nothing in it, I assume is the default for a WebView control. If I throw an actual URL in, the page loads up and works as expected, displaying the contents of the given website.

I believe it's simply not finding my page to display it. I'm building for Windows currently but this application will be eventually deployed to both Windows and Mac. How can I ensure it finds it correctly?

As pointed out below - I have also tried it this way, with the same result - when I click the link, I get a blank page.

                            <WebView x:Name="WebViewQuestionText" HeightRequest="500" WidthRequest="500">
                            <WebView.Source>
                                <HtmlWebViewSource>
                                    <HtmlWebViewSource.Html>
                                        <![CDATA[
            <html>
            <head>
            </head>
            <body>
            <h1>.NET MAUI</h1>
            <p>The CSS and image are loaded from local files!</p>
            <p><a href="editor.html">next page</a></p>
            </body>
            </html>                    
            ]]>
                                    </HtmlWebViewSource.Html>
                                </HtmlWebViewSource>
                            </WebView.Source>
                        </WebView>

My editor.html page is as follows:

<!DOCTYPE html>
<HTML>
    <BODY>
        <H1>This is a test</H1>
        <P>This is only a test</P>
    </BODY>
</HTML>
2
  • that is not what the docs you link to say to do. "Then, the file can be loaded from inline HTML that's defined in a HtmlWebViewSource object that's set as the value of the Source property:" learn.microsoft.com/en-us/dotnet/maui/user-interface/controls/… Commented Jun 13, 2022 at 19:15
  • 1
    I have tried that as well, with the same result, using the HTML in their example with the change of swapping my filename in place of theirs Commented Jun 13, 2022 at 19:17

4 Answers 4

6

I've fixed this with this PR into .Net Maui. Will be in the SR2 release due in the next few weeks.

The docs suggested it worked consistently on all platforms, but it simply had never been implemented on Windows... slightly concerning.

The workaround I've posted on the PR (mentioned also by Reinaldo below) will get around this for the mean time, however you should probably remove it once SR2 is released and you update to it.

Sign up to request clarification or add additional context in comments.

5 Comments

Is this fixed at the moment? I am about to create another question but want to confirm first. I can't even make the above code work in Android. When I click the link, it says file:///android_asset/index.html is not found.
This issue & PR relates only to Windows. I've been using same approach in Android without issue. I would check the following: 1. Is your index.html file in the /Resources/Raw folder. 2. Is its "Build Action" set to MauiAsset in the properties window? and/or; 3. Does your single-project csproj file have an <ItemGroup> element with the following in it: <MauiAsset Include="Resources\Raw\**" LogicalName="%(RecursiveDir)%(Filename)%(Extension)" />
In addition, if your index.html page loads other files (E.g. css/js) you may also need to write a global handler or hook into OnHandlerChanged event on your WebView to enable the following: protected void WebView_HandlerChanged(object sender, EventArgs e) { #if ANDROID var handler = (sender as Microsoft.Maui.Controls.WebView).Handler as Microsoft.Maui.Handlers.WebViewHandler; var webView = handler.PlatformView; webView.Settings.AllowFileAccessFromFileURLs = true; webView.Settings.AllowUniversalAccessFromFileURLs = true; #endif }
I don't think from memory those settings are necessary for just loading index.html, but if you're still having issues after trying steps 1-3, I'd give it a go.
Hi thanks for the response, turned out it was due to faulty template (or maybe I accidentally changed it without knowing). I don't know why it happens for that project but after creating new projec it works now :)
3

For those who come across this post 2022, which was prior to the SR2 release (see Breeno's answer); this is from a working app I got started on recently - you can load a local page directly with having to do the <HtmlWebViewSource> thing:

<WebView x:Name="webViewWiki" Source="/WikiContent/index.html" />

Where WikiContent is in /Resources/Raw folder in your solution structure, i.e.:

Solution structure in Visual Studio 2022

Relative links in your HTML to pages, images and stylesheets, will work as expected:

<html>
<head>
    <title>Test Index</title>
    <link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
    <h1>Index</h1>

    <h2>Vessel</h2>
    <ul>
        <li><a href="bgChartplotterGuide.html">Chart Plotter Guide</a></li>
    </ul>

    <h2>Physics</h2>
    <ul>
        <li><a href="physics_wind_in_sails.html">Physics: Wind in Sails Chart</a></li>
        <li><a href="anchoring.html">Anchoring</a></li>
        <li><a href="depth.html">Depth</a></li>
    </ul>

</body>
</html>

By the way:

The docs suggested it worked consistently on all platforms, but it simply had never been implemented on Windows... slightly concerning.

Lol, just slightly!

Comments

1

This ends up being a currently open bug against .NET MAUI on the Windows platform.

https://github.com/dotnet/maui/issues/5523

There appears to be a workaround here but it is not ideal. The issue appears to be one of resolving the correct path on Windows for the local file, so the workaround solution is to load the file directly via StreamReader

Comments

1

As mentioned before it is an open bug at the moment. However there is a workaround besides using a StreamReader.

#if WINDOWS
    private static readonly System.Lazy<bool> _isPackagedAppLazy = new System.Lazy<bool>(() =>
    {
        try
        {
            if (Windows.ApplicationModel.Package.Current != null)
                return true;
        }
        catch
        {
            // no-op
        }

        return false;
    });

    private static bool IsPackagedApp => _isPackagedAppLazy.Value;

    // Allow for packaged/unpackaged app support
    string ApplicationPath => IsPackagedApp
        ? Windows.ApplicationModel.Package.Current.InstalledLocation.Path
        : System.AppContext.BaseDirectory;
#endif

    private async void WebView_HandlerChanged(object sender, EventArgs e)
    {
#if WINDOWS            
        await ((sender as WebView).Handler.PlatformView as Microsoft.Maui.Platform.MauiWebView).EnsureCoreWebView2Async();
        ((sender as WebView).Handler.PlatformView as Microsoft.Maui.Platform.MauiWebView).CoreWebView2.SetVirtualHostNameToFolderMapping(
                "localhost",
                ApplicationPath,
                Microsoft.Web.WebView2.Core.CoreWebView2HostResourceAccessKind.Allow);
        var wv = (sender as WebView).Handler.PlatformView as Microsoft.Maui.Platform.MauiWebView;
        wv.LoadUrl($"https://localhost/{wv.Source.AbsolutePath}");

#endif
     }

The WebView would look something like this:

<WebView x:Name="dashBoardWebView" BackgroundColor="Transparent"  
                HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand"
                IsVisible="True"
             HandlerChanged="WebView_HandlerChanged"
             Source="test.html"></WebView>

Hope it helps.

Note: Taken from https://github.com/dotnet/maui/pull/7672

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.