• Stars
    star
    206
  • Rank 189,721 (Top 4 %)
  • Language
    C#
  • License
    MIT License
  • Created almost 2 years ago
  • Updated about 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

.NET MAUI HybridWebView experiment

This repo has the experimental .NET MAUI HybridWebView control, which enables hosting arbitrary HTML/JS/CSS content in a WebView and enables communication between the code in the WebView (JavaScript) and the code that hosts the WebView (C#/.NET). For example, if you have an existing React JS application, you could host it in a cross-platform .NET MAUI native application, and build the back-end of the application using C# and .NET.

Example usage of the control:

<hwv:HybridWebView
    HybridAssetRoot="hybrid_root"
    MainFile="hybrid_app.html"
    RawMessageReceived="OnHybridWebViewRawMessageReceived" />

And here's how .NET code can call a JavaScript method:

var sum = await myHybridWebView.InvokeJsMethodAsync<int>("JsAddNumbers", 123, 456);

And the reverse, JavaScript code calling a .NET method:

HybridWebView.SendInvokeMessageToDotNet("CallMeFromScript", ["msg from js", 987]);

In addition to method invocation, sending "raw" messages is also supported.

What's in this repo?

Projects in this repo:

  • HybridWebView --> a cross-platform .NET MAUI control that can load static web assets (HTML, JS, CSS, etc.) and send messages between JavaScript and .NET
  • MauiCSharpInteropWebView --> a sample app that shows the basic functionality of sending messages and calling methods between JavaScript and .NET
  • MauiReactJSHybridApp --> a sample app that incorporates a pre-existing React-based todo application into a .NET MAUI cross-platform application

Discussions/questions/comments

See the main discussion topic here: dotnet/maui#12009

Or please log an issue in this repo for any other topics.

Getting Started

To get started, you'll need a .NET MAUI 7 project, then add the HybridWebView control, and add some web content to it.

Note: If you'd like to check out an already completed sample, go to https://github.com/Eilon/SampleMauiHybridWebViewProject

  1. Ensure you have Visual Studio 2022 with the .NET MAUI workload installed
  2. Create a .NET MAUI App project that targets .NET 7 (or use an existing one)
  3. Add a reference to the EJL.MauiHybridWebView package:
    1. Right-click on the Dependencies node in Solution Explorer and select Manage NuGet Packages
    2. Select the Browse tab
    3. Ensure the Include prerelease checkbox is checked
    4. In the search box enter ejl.mauihybridwebview
    5. Select the matching package, and click the Install button
  4. Register and add the HybridWebView control to a page in your app:
    1. In MauiProgram.cs add the line builder.Services.AddHybridWebView(); to register the HybridWebView components
    2. Open the MainPage.xaml file
    3. Delete the <ScrollView> control and all of its contents
    4. Add a xmlns:ejl="clr-namespace:HybridWebView;assembly=HybridWebView" declaration to the top-level <ContentPage ....> tag
    5. Add the markup <ejl:HybridWebView HybridAssetRoot="hybrid_root" RawMessageReceived="OnHybridWebViewRawMessageReceived" /> inside the <ContentPage> tag
    6. Open the MainPage.xaml.cs file
    7. Delete the count field, and the OnCounterClicked method, and replace it with the following code:
      private async void OnHybridWebViewRawMessageReceived(object sender, HybridWebView.HybridWebViewRawMessageReceivedEventArgs e)
      {
          await Dispatcher.DispatchAsync(async () =>
          {
              await DisplayAlert("JavaScript message", e.Message, "OK");
          });
      }
  5. Now add some web content to the app:
    1. In Solution Explorer expand the Resources / Raw folder
    2. Create a new sub-folder called hybrid_root
    3. In the hybrid_root folder add a new file called index.html and replace its contents with:
      <!DOCTYPE html>
      
      <html lang="en" xmlns="http://www.w3.org/1999/xhtml">
      <head>
          <meta charset="utf-8" />
          <title></title>
          <script src="_hwv/HybridWebView.js"></script>
          <script src="myapp.js"></script>
      </head>
      <body>
          <div>
              Your message: <input type="text" id="messageInput" />
          </div>
          <div>
              <button onclick="SendMessageToCSharp()">Send to C#!</button>
          </div>
      </body>
      </html>
    4. In the same folder add another file myapp.js with the following contents:
      function SendMessageToCSharp() {
          var message = document.getElementById('messageInput').value;
          HybridWebView.SendRawMessageToDotNet(message);
      }
  6. You can now run your .NET MAUI app with the HybridWebView control!
    1. You can run it on Windows, Android, iOS, or macOS
    2. When you launch the app, type text into the textbox and click the button to receive the message in C# code

How to run the source code in this repo

To run this app you need to have Visual Studio for Windows or Mac, including the .NET MAUI workload. Then clone this repo, open the solution, and run one of the sample projects.

MauiReactJSHybridApp React JS app

The MauiReactJSHybridApp sample contains portions of a pre-existing Todo App built using React JS.

The original React JS Todo app sample used here is based on this sample: https://github.com/mdn/todo-react. I created a fork at https://github.com/Eilon/todo-react that incorporates some small changes to call the .NET API from JavaScript to synchronize the Todo list between the two parts of the app.

To make changes to the fork and update the .NET MAUI app, here's what I do:

  1. Clone of the forked repo and open a terminal/console window in that folder
  2. Run yarn to ensure the JavaScript dependencies are installed
  3. Run set PUBLIC_URL=/ to establish the root of the app as / because that's the root of the .NET MAUI HybridWebView app
  4. Run npm run build to compile the app and produce a static version of it
    • If you get this error: Error: error:0308010C:digital envelope routines::unsupported
    • Then run set NODE_OPTIONS=--openssl-legacy-provider
    • And run this again: npm run build
  5. This will build the HTML/JS/CSS output into a new ./build folder
  6. Go to the MauiReactJSHybridApp's Resources/Raw/ReactTodoApp folder and delete all the existing files, and replace with the files from the previous step's ./build folder
  7. Then run the MauiReactJSHybridApp from Visual Studio

This project is licensed under the MIT License. However, portions of the incorporated source code may be subject to other licenses:

More Repositories

1

CatTrackerDemo

Cat Tracker Demo
C#
41
star
2

Hubbup

ASP.NET Core app to view GitHub issues for team stand-up
C#
37
star
3

dotnetConf-BrickTracker

HTML
23
star
4

Rezipe

Recipe app built with Mobile Blazor Bindings
C#
17
star
5

MvpSummit2021-BlazorDesktop

C#
10
star
6

MauiSignalRGridDemo

HTML
8
star
7

BlazorHybridWebAppDotNet8

Sample .NET 8 app showing how to share Blazor components between an ASP.NET Blazor Web App and a .NET MAUI Blazor Hybrid app
CSS
6
star
8

MauiMicrochartsSample

C#
5
star
9

maui18548LoadingScreen

.NET MAUI Blazor Hybrid loading screen sample
CSS
5
star
10

MobileBlazorBindings-WindowsDesktop

Windows Desktop samples for Mobile Blazor Bindings
C#
4
star
11

BlazorHybridShareStateDemo

.NET Conf 2022 Blazor Hybrid state sharing demo
C#
4
star
12

QuirksModeSwitchSample

Sample showing how to enable AppContext switches on .NET Framework and .NET Core
C#
3
star
13

DotNetLabelerUploader

Tool to upload blobs for dotnet-issue-labeler
C#
3
star
14

IssueOpenerLabeler

GitHub Issue Opener Labeler Action
C#
3
star
15

NuGetPackageVerifier

C#
3
star
16

MauiBlazorWebSolution

Template variations for .NET MAUI Blazor Hybrid + Web App solution
C#
3
star
17

MauiIssueProcessor

C#
2
star
18

Rexipe

Rexipe mobile app for managing recipes
C#
2
star
19

XamarinThemeChange

Repro for theme change bug
C#
2
star
20

SampleMauiHybridWebViewProject

Sample project for HybridWebView
C#
2
star
21

maui19822headcontent

Blazor Hybrid HeadOutlet sample for maui#19822
CSS
2
star
22

GraphQLDemo

GraphQL demo with .NET Core, ASP.NET Core, EF Core, and more
C#
2
star
23

MobileBlazorBindingsMigration

Template snapshots for Mobile Blazor Bindings
C#
2
star
24

EdSampleBlazor

C#
1
star
25

SuperStartupBuilder

C#
1
star
26

GetYouTubeStats

C#
1
star
27

OutlookFinder

App to tag interesting Outlook items
C#
1
star
28

ThirdPartyNoticesGenerator

Generator for 3rd Party Notices file
C#
1
star
29

SyncFusionThemesBlazorWinFormsApp

C#
1
star
30

ShellNullRef

C#
1
star
31

XamarinGitHubViewer

Xamarin GitHub Viewer
C#
1
star
32

MauiBlazorHybridEmpty

Sample repo showing difference of Empty option in .NET MAUI 9
C#
1
star
33

DragDropWinFormsApp2

Repro apps for MAUI issue 3395
C#
1
star
34

GetShippedAspNetPackages

C#
1
star
35

XFTransitiveMismatch

C#
1
star
36

AddMessageNotificationSample

C#
1
star