Maui Blazor 中文社区 QQ群:645660665

Maui 内嵌网页直接调用本机原生功能 Demo

使用 MAUI 制作 H5 套壳程序有以下几个好处:

  1. 跨平台支持:MAUI (Multi-platform App UI) 允许开发者在多个平台(如 iOS、Android、Windows 和 macOS)上运行应用程序。

  2. 统一封装的MauiPlus库可以统一调用本机功能,确保在不同平台上有一致的用户体验。

  3. 访问本地功能:MauiPlus库提供了对设备本地功能(如相机、传感器、文件系统等)的访问接口,使得 H5 应用可以通过本库轻松调用这些功能,增强应用的能力。

  4. 性能优化:相比于纯 H5 应用,MauiPlus库可以更好地利用本地资源和硬件加速,提升应用的性能和响应速度。

  5. H5 应用有丰富的控件库,例如 Bootstrap Blazor UI, VUE:可以更方便地构建复杂的用户界面,提升开发效率。

demo

  1. 新建Maui工程 MauiPlusDemo
  2. 添加nuget包 Densen.MauiPlus
  3. 编辑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"
             x:Class="MauiPlusDemo.MainPage">

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

</ContentPage>
  1. 编辑代码MainPage.xaml.cs文件
using MauiPlus;

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

        public MainPage()
        {
            InitializeComponent();

            //附加本机功能处理
            WebView? wvBrowser = FindByName("webView") as WebView;
            if (wvBrowser != null)
            {
                LoadHtmlToWebView(wvBrowser);
                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
        }

        private async void LoadHtmlToWebView(WebView wvBrowser)
        {
            // 加载本地 HTML 文件
            var htmlSource = new HtmlWebViewSource
            {
                BaseUrl = FileSystem.AppDataDirectory,
                Html = await LoadLocalHtml("demo.html")
            };
            wvBrowser.Source = htmlSource;
        }

        private async Task<string> LoadLocalHtml(string fileName)
        {
            using var stream = await FileSystem.OpenAppPackageFileAsync(fileName);
            using var reader = new StreamReader(stream);

            var contents = await reader.ReadToEndAsync();
            return contents;
        }
    }

}
  1. 新建测试页面
    Resources/raw/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>
  1. 运行

  2. 更多

开源工程

https://github.com/densen2014/BlazorHybrid?WT.mc_id=DT-MVP-5005078

快速开发共享代码库运行于 Windows (Winforms/WPF/UWP)、Android、iOS、macOS、Linux 的应用。

posted @   AlexChow  阅读(90)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek-R1本地部署如何选择适合你的版本?看这里
· 传国玉玺易主,ai.com竟然跳转到国产AI
· 自己如何在本地电脑从零搭建DeepSeek!手把手教学,快来看看! (建议收藏)
· 我们是如何解决abp身上的几个痛点
· 普通人也能轻松掌握的20个DeepSeek高频提示词(2025版)
点击右上角即可分享
微信分享提示