.Net6 WPF 使用 WebView2套壳,js调用api

1.初始化

using api;
using System;
using System.Windows;

namespace WpfApp2
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            if (webView != null)
            {
                webView.Source = new Uri(Environment.CurrentDirectory + @"\web\mypage.html");
                InitializeAsync();
            }
        }

        public async void InitializeAsync()
        {
            //等待CoreWebView2对象就绪,否则为null
            await webView.EnsureCoreWebView2Async();
            webView.CoreWebView2.AddHostObjectToScript("webapi", new ScriptCallbackObject());
            //直接将api定义到页面中,调用直接使用webapi.xxxx()
            await webView.CoreWebView2.ExecuteScriptAsync("var webapi = window.chrome.webview.hostObjects.webapi;");
            //禁止鼠标缩放
            webView.CoreWebView2.Settings.IsZoomControlEnabled = false;
        }
    }
}

2.定义接口

using System.Runtime.InteropServices;

namespace api
{
    /// <summary>
    /// 提供给web页面的api
    /// </summary>
    [ClassInterface(ClassInterfaceType.None)]
    [ComVisible(true)]
    public class ScriptCallbackObject
    {
        public string GetData(string arg)
        {
            return "获取到了:" + arg;
        }
    }
}

3.页面调用

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <h3>有点扯淡哦</h3>
    <input type="text" id="input" />
    <button onclick="myclick()">事件aaaa</button>
    <script type="text/javascript">
        async function myclick() {
            var data = document.getElementById('input').value;
            console.log(webapi);
            var result = await webapi.GetData(data);
            alert(result);
        }
    </script>
</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值