BlazorHybrid 通过Blazor简单调用本机功能

news/2024/10/16 2:30:01

简单调用本机功能,例如打印,获取硬件信息,获取本机用户名,拦截JS功能,拦截错误信息等等..

废话不多说先来截图

使用 JsBridge

JsBridge不科普了,同学们自行百度一下

BlazorWebView.cs

using Microsoft.AspNetCore.Components.WebView;
using Microsoft.AspNetCore.Components.WebView.WindowsForms;
using Microsoft.VisualBasic.ApplicationServices;
using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.WinForms;
using System.Runtime.InteropServices;
using WebView2Control = Microsoft.Web.WebView2.WinForms.WebView2;public partial class InitBlazorWebView
{BlazorWebView _blazorWebView;public InitBlazorWebView(BlazorWebView blazorWebView){_blazorWebView = blazorWebView;_blazorWebView.BlazorWebViewInitialized += BlazorWebViewInitialized;}void BlazorWebViewInitialized(object sender, BlazorWebViewInitializedEventArgs e){//使用 JsBridgeInitializeBridgeAsync(e.WebView);}#region JsBridgestatic BridgeObject obj = new BridgeObject();/// <summary>/// 自定义宿主类,用于向网页注册C#对象,供JS调用/// </summary>[ClassInterface(ClassInterfaceType.AutoDual)][ComVisible(true)]public class Bridge{public string Func(string param) => $"Func返回 {param} {obj.MacAdress}";public string Print(object param) => $"Print返回 {param}";public void PrintDemo(object param) => MessageBox.Show($"Print {param}");public void Alert(string param) => MessageBox.Show(param);public string GetUserName() => Environment.MachineName + "/" + Environment.UserDomainName + "/" + System.Windows.Forms.SystemInformation.UserName  ;}public class BridgeObject{public string MacAdress => $"{DateTime.Now:G}";}async void InitializeBridgeAsync(WebView2Control webView){webView.CoreWebView2.AddHostObjectToScript("bridge", new Bridge());await webView.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync("var bridge= window.chrome.webview.hostObjects.bridge;");await webView.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync($"localStorage.setItem('macAdress', '{obj.MacAdress}')");}#endregion
}

Blazor测试组件

Tips: 不一定要在win端执行,在远端部署也可以的.

JsBridge.razor

@using BootstrapBlazor.Components<GroupBox Title="Bridge"><Button Text="GetMacAdress" OnClick="GetMacAdress" IsDisabled="!BridgeEnabled" /><Button Text="Print" OnClick="OnPrint" IsDisabled="!BridgeEnabled" /><Button Text="用户名" OnClick="GetUserName" IsDisabled="!BridgeEnabled" />
</GroupBox><GroupBox Title="拦截JS"><button class="btn btn-primary" role="button" onclick="alert('来自Blazor的alert警告框')">Alert</button><button class="btn btn-primary" role="button" onclick="console.error('You made a mistake')">console.error</button><button class="btn btn-primary" role="button" onclick="print('来自Blazor的print')">Print</button>
</GroupBox>
<pre> 
@message
</pre>

JsBridge.razor.cs

public partial class JsBridge
{string? message;bool BridgeEnabled;[Inject, NotNull]IJSRuntime? JS { get; set; }[Inject, NotNull]ToastService? ToastService { get; set; }[Inject, NotNull]IJSRuntime? JS { get; set; }[Inject, NotNull]ToastService? ToastService { get; set; }//private IJSObjectReference? module;async Task GetMacAdress(){//message = await module!.InvokeAsync<string>("GetMacAdress");//await ToastService.Information("JS方式 macAdress", message);message = await JS!.InvokeAsync<string>("eval", $"localStorage.getItem('macAdress');");await ToastService.Information("eval macAdress", message);message = await JS!.InvokeAsync<string>("eval", "bridge.Func('测试')");await ToastService.Information("eval bridge.Func", message);}async Task OnPrint(){message = await JS!.InvokeAsync<string>("eval", $"bridge.Print('打印文本123456789')");await ToastService.Information("eval bridge.Print", message);message = await JS!.InvokeAsync<string>("eval", $"bridge.Print({ItemsPrint.ObjectToJson()})");await ToastService.Information("eval bridge.Print object", message);}async Task GetUserName(){message = await JS!.InvokeAsync<string>("eval", $"bridge.GetUserName()");await ToastService.Information("eval bridge.GetUserName", message);}string[] ItemsPrint = ["Item1", "Item2", "Item3"];protected override async Task OnAfterRenderAsync(bool firstRender){try{if (firstRender){BridgeEnabled = await JS!.InvokeAsync<bool>("eval", $"typeof bridge != 'undefined'");message = await JS!.InvokeAsync<string>("eval", $"localStorage.getItem('macAdress');");}}catch (Exception e){message = e.Message;}StateHasChanged();}}

win端js拦截方式

BlazorHybrid.Win/wwwroot/jsbridge.js

function alert(message) {console.info(message);if (bridge != null) {//调用C#方法bridge.Alert(message);}
} var oldPrintFunction = window.print;
var oldConsoleErrorFunction = console.error;window.print = function (e) {console.log('Gonna do some special stuff');if (bridge != null) {//调用C#方法bridge.PrintDemo('打印对象示例: '+e);} else {oldPrintFunction();}
};
console.error = function (e) {if (bridge != null) {//调用C#方法bridge.Alert(e);} else {oldConsoleErrorFunction(e);}
};function beforePrint() {console.log('Do something special before print');
}function afterPrint() {console.log('Do something after print');
}if (window.matchMedia) {window.matchMedia('print').addListener(function (mql) {if (mql.matches) {beforePrint();}else {afterPrint();}});
}// For IE, does not attach in browsers that do not support these events
window.addEventListener('beforeprint', beforePrint, false);
window.addEventListener('afterprint', afterPrint, false);

BlazorHybrid.Win/wwwroot/index.html

    <script src="jsbridge.js"></script>

欢迎大佬加入Maui Blazor 中文社区QQ群 645660665 ,感谢star 相关开源项目

群项目快速入门
https://github.com/densen2014/BlazorHybrid/blob/master/快速上手.md?wt.mc_id=DT-MVP-5005078

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.ryyt.cn/news/41583.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈,一经查实,立即删除!

相关文章

一文搞懂 ARM 64 系列: 一文搞懂 ARM 64 系列: 函数调用传参与返回值

一文搞懂 ARM 64 系列: 一文搞懂 ARM 64 系列: 函数调用传参与返回值函数调用涉及到传参与返回值,下面就来看下ARM 64中,参数与返回值的传递机制。 1 整数型参数传递 这里的整数型并不单指int类型,或者NSInteger类型,而是指任何能够使用整数表示的数据类型,包括char、BOOL…

4~6次题目集总结blog

一、前言 关于家具电路系统和答题判题系统我认为最主要的难点在于类设计,我们先需要设计好父类再对子类和具体方法进行补充,就拿电路系统举例,无论是受控设备还是控制设备,具体代码都较为简单,只需简单的数学运算就能求出具体功率,但要如何将设备加入电路当中以及能够进行…

oracle 基本查询

建表语句 序列 create sequence seq_jx increment by 1 start with 1 nomaxvalue nominvalue cache 10;字典类型表 create table sys_dict_type( id number(20) primary key, name varchar2(100) , type varchar2(100) , group_code varchar2(100) , status char(1) );comment…

VMware常用操作

VMware常用操作 VMware作为一款功能强大的虚拟化软件,为用户提供了一个灵活、高效的虚拟环境。在日常使用中,掌握VMware的常用操作对于提高工作效率、优化资源配置至关重要。以下将详细介绍VMware的一些常用操作及其背后的原理。 一、文件操作 在VMware中,文件操作是最基本的…

Kafka 基础知识

在数据事件流方面,Apache Kafka 是事实上的标准。它是一个由服务器和客户端组成的开源分布式系统。Apache Kafka 主要用于构建实时数据流管道。 Apache Kafka 被全球数以千计的领先组织用于高性能数据管道、流分析、数据集成和许多其他重要应用程序。 在本节中,我们将学习所有…

python-数据分析-NumPy的应用-1、基础

1、安装python 数据分析的三大神器 pip install numpy pandas matplotlibNumpPy 的说明 Numpy 是一个开源的 Python 科学计算库,用于快速处理任意维度的数组。Numpy 支持常见的数组和矩阵操作、 对于同样的数值计算任务,使用 NumPy 不仅代码要简洁的多,而且 NumPy 在性能上也…

安装VMware

安装VMware 官网下载 首先需要进行账号注册:https://support.broadcom.com/注册完成后,进行账号登录:https://login.broadcom.com/signin 此处登录的用户名为注册邮箱登录后按照下图点击选择VMware的版本勾选同意后,点击下载安装VMware 无脑安装即可安装包下载 如果不想注册…

鸿蒙前端开发1-基本设置

1.AppScope>app.json5 中的icon和label设置,位置手机>设置>应用显示的图标和名称。标签值为字符串资源的索引,不能直接写名字,应该在字符串资源中设置 2.entry>configuration.json5中的icon和label设置的是应用安装后在桌面显示的图标和名称 3.