dotnet / docs-maui

This repository contains documentation for .NET Multi-platform App UI (MAUI).
https://docs.microsoft.com/dotnet/maui
Creative Commons Attribution 4.0 International
222 stars 194 forks source link

HybridWebView Docs: Overview #2433

Open BethMassi opened 1 month ago

BethMassi commented 1 month ago

Overview

BethMassi commented 1 month ago

@davidbritch I don't have permissions to assign this to myself. I'm working on this and should have draft content posted here tomorrow.

davidbritch commented 1 month ago

@BethMassi I've assigned to you, but I've also added you to the relevant group that should give you the permissions you need.

Eilon commented 1 month ago

From @Eilon :

Getting Started with HybridWebView

To build a .NET MAUI app with HybridWebView you need a few pieces:

  1. The web content of the app, which consists of static HTML, JavaScript, CSS, images, and other files.
  2. Using the HybridWebView control as part of the app's UI, such as by referencing it in the app's XAML.
  3. Adding code to the "web" portion and the C#/.NET portion of the app to use the HybridWebView's APIs to send messages between them, thus making it a hybrid application.

The entire app, including the web content, is packaged and then runs locally on the device, and can be published to applicable app stores. The web content is hosted within a native web view control and runs within the context of the app. Any part of the app can access external web services, but it is not required.

Create a new project

Create a new .NET MAUI Application project in Visual Studio, Visual Studio Code, or using command line tools.

Adding web content to the app

Your app's web content is included as part of the .NET MAUI project as "raw assets." A raw asset is any file in the app's Resources\Raw folder, including sub-folders.

For HybridWebView the default location is to place files in the Resources\Raw\wwwroot folder, with the main file named index.html.

A simple application might have the following files and contents:

Resources\Raw\wwwroot\index.html with content for the main UI:

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
    <link rel="icon" href="data:,">
    <script src="scripts/HybridWebView.js"></script>
    <script>
        window.addEventListener(
            "HybridWebViewMessageReceived",
            function (e) {
                var messageFromCSharp = document.getElementById("messageFromCSharp");
                messageFromCSharp.value += '\r\n' + e.detail.message;
            });
    </script>
</head>
<body>
    <h1>HybridWebView app!</h1>
    <div>
        <button onclick="window.HybridWebView.SendRawMessage('Message from JS!')">Send message to C#</button>
    </div>
    <div>
        Messages from C#: <textarea readonly id="messageFromCSharp" style="width: 80%; height: 300px;"></textarea>
    </div>
</body>
</html>

Resources\Raw\wwwroot\scripts\HybridWebView.js with the standard HybridWebView JavaScript library:

function HybridWebViewInit() {

    function DispatchHybridWebViewMessage(message) {
        const event = new CustomEvent("HybridWebViewMessageReceived", { detail: { message: message } });
        window.dispatchEvent(event);
    }

    if (window.chrome && window.chrome.webview) {
        // Windows WebView2
        window.chrome.webview.addEventListener('message', arg => {
            DispatchHybridWebViewMessage(arg.data);
        });
    }
    else if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.webwindowinterop) {
        // iOS and MacCatalyst WKWebView
        window.external = {
            "receiveMessage": message => {
                DispatchHybridWebViewMessage(message);
            }
        };
    }
    else {
        // Android WebView
        window.addEventListener('message', arg => {
            DispatchHybridWebViewMessage(arg.data);
        });
    }
}

window.HybridWebView = {
    "SendRawMessage": function (message) {

        if (window.chrome && window.chrome.webview) {
            // Windows WebView2
            window.chrome.webview.postMessage(message);
        }
        else if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.webwindowinterop) {
            // iOS and MacCatalyst WKWebView
            window.webkit.messageHandlers.webwindowinterop.postMessage(message);
        }
        else {
            // Android WebView
            hybridWebViewHost.sendRawMessage(message);
        }
    }
}

HybridWebViewInit();

And you can then add any other files for CSS, images, additional HTML files, and so on.

TIP: In some cases the IDE or code editor might add entries to the project's .csproj file that are incorrect. When using the default locations for the raw assets there should be no entries for any of these files or folders in the .csproj file. You might need to look at source control diffs to undo any such changes.

Adding the HybridWebView control

In the app's MainPage.xaml file replace the default code within the <ContentPage> tag with this XAML that has a grid layout, a button, and the HybridWebView control:

  <Grid RowDefinitions="Auto,*" ColumnDefinitions="*">
    <Button Text="Send message to JavaScript" Clicked="OnSendMessageButtonClicked" />

    <HybridWebView x:Name="hybridWebView" RawMessageReceived="OnHybridWebViewRawMessageReceived" Grid.Row="1" />
  </Grid>

Use HybridWebView APIs to send messages between the JavaScript and C# code

The sample HTML code above already include JavaScript code to send messages to the C# code.

Edit the MainPage.xaml.cs file and replace the default counter code with the following code to send and receive messages:

    private void OnSendMessageButtonClicked(object sender, EventArgs e)
    {
        hybridWebView.SendRawMessage($"Hello from C#!");
    }

    private async void OnHybridWebViewRawMessageReceived(object sender, HybridWebViewRawMessageReceivedEventArgs e)
    {
        await DisplayAlert("Raw Message Received", e.Message, "OK");
    }

The message are "raw" because no additional processing is performed. You can encode data within the message to perform more advanced messaging.

Future of HybridWebView

Future updates will include the ability to invoke methods from C# to JavaScript, and also from JavaScript to C#.

BethMassi commented 1 month ago

This article explains .NET MAUI hybrid apps, a way to build cross-platform native apps that use web UI.

What are Hybrid apps?

Hybrid apps provide native experiences across multiple device platforms but use web technologies for building the UI. The UI is packaged with the app, and you have full access to the native device capabilities. This approach also allows you to reuse UI assets across devices and web browsers.

Hybrid apps are a blend of both native and web solutions. The core UI of the application is written using web technologies such as HTML, CSS, and JavaScript. These apps are then wrapped in a lightweight native app container that allows them to leverage certain native platform features and device hardware (like a device's camera, calendar, push notifications, and pinch and spread functionality) that a web application cannot access easily or even at all.

This approach allows hybrid apps to run on, for example, both iOS and Android platforms without the need for completely separate development. And they can be downloaded and installed through the app stores. The main advantage of hybrid apps is that they can achieve greater developer productivity via code reuse across devices and web browsers.

.NET MAUI Hybrid App Options

With .NET MAUI you can either host Blazor components with the BlazorWebView control or any other HTML/JavaScript-based UI with the HybridWebView control. These controls derive from the native platform’s WebView. No internet is required; your UI is packaged with the app. This makes it easier to share UI across native and web hosting models. Hybrid apps rely on .NET MAUI for a native application container and native controls, if you want to use them. This means you can mix web UI with native UI if you want. .NET MAUI Hybrid apps can also be packaged for store distribution whether that’s the Microsoft, Apple or Google App stores.

.NET MAUI Blazor Hybrid apps also have additional controls, templates and tooling in Visual Studio and Visual Studio Code to make development easier. For more information on .NET MAUI Blazor Hybrid apps see the ASP.NET Core Blazor Hybrid docs.

.NET MAUI Blazor Hybrid Tutorials

Getting Started with HybridWebView

// Eilon's stuff above goes here