Maui Blazor 中文社区 QQ群:645660665

另辟新径实现 Blazor/MAUI 本机交互(四)

实战

老规矩,先上源码

新建项目, 搜索 blazor, 选择 .NET Maui Blazor 应用

TIPS: 因为之后需要本机blazor做配置页面,所以这里演示使用了.NET Maui Blazor 应用. 如果不需要本机blazor UI, 建立普通.NET Maui 应用也能使用.

输入项目名称 MauiBridge

因为net9.0使用的js标准太新,导致旧版安卓机器(特别是工业条码采集器,带打印头那种)无法初始化,所以我们选net8.0建立演示工程

[.NET 9] BlazorWebView 无法在较旧的 Android 设备上加载

NativeBridge 类

新建Services文件夹,放入前面文章的两个文件

  1. WebViewNativeApi.cs
  2. NativeApi.cs

修改主页面

暂时移除BlazorWebView相关代码,从简单WebView容器入手演示功能

编辑页面 MainPage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:MauiBridge"
             x:Class="MauiBridge.MainPage">

    <WebView x:Name="webView" Source="wwwroot/demo.html" HeightRequest="700" />

    <!--<BlazorWebView x:Name="blazorWebView" HostPage="wwwroot/index.html">
        <BlazorWebView.RootComponents>
            <RootComponent Selector="#app" ComponentType="{x:Type local:Components.Routes}" />
        </BlazorWebView.RootComponents>
    </BlazorWebView>-->

</ContentPage>

MainPage.xaml.cs

编辑页面 MainPage.xaml.cs 代码

using WebViewNativeApi;

namespace MauiBridge
{
    public partial class MainPage : ContentPage
    {
        private NativeBridge? api;

        public MainPage()
        {
            InitializeComponent();

            //附加本机功能处理
            WebView? wvBrowser = FindByName("webView") as WebView;
            api = new NativeBridge(wvBrowser);
            api.AddTarget("dialogs", new NativeApi());
#if MACCATALYST
        Microsoft.Maui.Handlers.WebViewHandler.Mapper.AppendToMapping("Inspect", (handler, view) =>
        {
            if (OperatingSystem.IsMacCatalystVersionAtLeast(16, 6))
                handler.PlatformView.Inspectable = true;
        });
#endif
        }
    }
}

页面调用功能

添加文件 wwwroot\demo.html

<!DOCTYPE html>
<html lang="en" data-bs-theme='light'>

<head>
    <meta charset="utf-8" />
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
    <title>Native API</title>
</head>
<body>

    <div style='display: flex; flex-direction: column; justify-content: center; align-items: center; width: 100%'>
        <h2 style='font-family: script'><i>Hybrid WebView</i></h2>
        <div id='webtext' style='font-family: script'><b>Native API</b></div><br />
        <button style='height:48px; margin-left: 15px; margin-right: 15px; width: 128px; background: lightblue' id='hereBtn' onclick='setConfig()'>setConfig</button>
        <button style='height:48px; margin-left: 15px; margin-right: 15px; width: 128px; background: lightblue' id='hereBtn' onclick='getConfig()'>getConfig</button>
        <button style='height:48px; margin-left: 15px; margin-right: 15px; width: 128px; background: lightblue' id='hereBtn' onclick='openDialog()'>openDialog</button>
        <button style='height:48px; margin-left: 15px; margin-right: 15px; width: 128px; background: lightblue' id='hereBtn' onclick='saveFile()'>saveFile</button> 
    </div>

    <script> 

        function setConfig() {
            var name = Math.ceil(Math.random() * 10).toString();
            var promise = window.dialogs.set_config(name);
            runCommand(promise);
        }

        function getConfig() {
            var promise = window.dialogs.get_config();
            runCommand(promise);
        }

        function openDialog() {
            var promise = window.dialogs.open_file_dialog();
            runCommand(promise, true);
        }

        function saveFile() {
            var promise = window.dialogs.save_file("test file", "test.txt");
            runCommand(promise);
        } 

        function runCommand(promise, isEncode = false) {
            promise.then((fileData) => {
                let text = isEncode ? atob(fileData) : (fileData.Result !== undefined ? fileData.Result : fileData);
                var el = document.getElementById('webtext');
                el.innerHTML = text;
                console.log(text);
            });
        }
         
    </script>
</body>
</html> 

运行

posted @ 2025-02-11 20:22  AlexChow  阅读(2367)  评论(0)    收藏  举报