Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

HybridWebView Docs: Overview #2433

Open
BethMassi opened this issue Aug 8, 2024 · 8 comments
Open

HybridWebView Docs: Overview #2433

BethMassi opened this issue Aug 8, 2024 · 8 comments
Assignees
Labels
doc-idea Indicates issues that are suggestions for new topics [org] Pri3 📌 seQUESTered Identifies that an issue has been imported into Quest.

Comments

@BethMassi
Copy link
Contributor

BethMassi commented Aug 8, 2024

Overview
- What are MAUI hybrid apps?, explain options: HybridWebView or BlazorWebView, point to blazor/hybrid docs for BlazorWebView
- Getting started / set up HybridWebView
- Suggested project structure (VS / VS Code differences)
- WebView config
- passing messages / calling methods to JS <-> C#
- Globalization / localization? (probably not needed or needed later)


Associated WorkItem - 370907

@dotnet-bot dotnet-bot added the ⌚ Not Triaged Not triaged label Aug 8, 2024
@BethMassi
Copy link
Contributor Author

@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 davidbritch added doc-idea Indicates issues that are suggestions for new topics [org] 🏁 Release: .NET 9 Work items for the .NET 9 release and removed Pri3 ⌚ Not Triaged Not triaged labels Aug 8, 2024
@davidbritch
Copy link
Contributor

@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
Copy link
Member

Eilon commented Aug 8, 2024

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:

NOTE: The contents of this file change with each version (and pre-release) of .NET MAUI, so check that the content matches the latest release. The content below is from .NET 9 Preview 7.

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
Copy link
Contributor Author

BethMassi commented Aug 8, 2024

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

@davidbritch davidbritch removed the Pri3 label Aug 9, 2024
@nine-2-five
Copy link

[chromium] [INFO:CONSOLE(43)] "Uncaught TypeError: hybridWebViewHost.sendRawMessage is not a function", source: https://0.0.0.0/scripts/HybridWebView.js (43)

@Eilon
Copy link
Member

Eilon commented Sep 17, 2024

@nine-2-five the preview doc listed above is out-of-date now. Check that you have the latest HybridWebView.js content for .NET 9 RC1 per this comment: dotnet/maui#24705 (comment)

We'll make sure the docs are up-to-date!

@BethMassi
Copy link
Contributor Author

@davidbritch what are the next steps for getting a /hybrid/ section in the TOC with the intro/overview above that explains BlazorWebView and HybridWebView options? Can we mirror the blazor/hybrid section docs into maui/hybrid/blazor or something similar here?

@davidbritch davidbritch removed the Pri3 label Feb 6, 2025
@dotnetrepoman dotnetrepoman bot added the ⌚ Not Triaged Not triaged label Feb 6, 2025
@davidbritch davidbritch added 🗺️ reQUEST Triggers an issue to be imported into Quest. doc-idea Indicates issues that are suggestions for new topics [org] and removed doc-idea Indicates issues that are suggestions for new topics [org] ⌚ Not Triaged Not triaged 🏁 Release: .NET 9 Work items for the .NET 9 release labels Feb 6, 2025
@davidbritch davidbritch self-assigned this Feb 6, 2025
@davidbritch
Copy link
Contributor

@BethMassi

what are the next steps for getting a /hybrid/ section in the TOC with the intro/overview above that explains BlazorWebView and HybridWebView options?

I'll do it next week.

Can we mirror the blazor/hybrid section docs into maui/hybrid/blazor or something similar here?

Yes.

@sequestor sequestor bot added 📌 seQUESTered Identifies that an issue has been imported into Quest. and removed 🗺️ reQUEST Triggers an issue to be imported into Quest. labels Feb 7, 2025
@dotnetrepoman dotnetrepoman bot added ⌚ Not Triaged Not triaged and removed ⌚ Not Triaged Not triaged labels Feb 7, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
doc-idea Indicates issues that are suggestions for new topics [org] Pri3 📌 seQUESTered Identifies that an issue has been imported into Quest.
Projects
Status: Todo
Development

No branches or pull requests

5 participants