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>