CefSharp.WPF+JS相互之间数据传递
1.CefSharp 117.2.40
2.Html代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1 id="h1Test">CefSharp+HTML+JS绑定测试</h1>
<input id="btn1Test" type="button" value="测试同步绑定"/>
<input id="btn2Test" type="button" value="测试异步绑定"/>
<div id="divText"></div>
<script>
btn1Test.onclick = function ()
{
JsObj.setMessageSync("新消息").then({});
JsObj.showMessageAsync().then({});
JsObj.getMessageAsync().then(msg => {
console.log(msg);
});
JsObj.getCurrTimeAsync().then(t => {
console.log(t);
divText.innerHTML = "当前时间为:" + t;
});
}
btn2Test.onclick = async function ()
{
await JsObj.setMessageAsync("新消息");
await JsObj.showMessageAsync();
let msg = await JsObj.getMessageAsync();
console.log(msg);
let t = await JsObj.getCurrTimeAsync();
console.log(t);
divText.innerHTML = "当前时间为:" + t;
}
</script>
</body>
</html>
3.C#关键代码
CefSharpSettings.ConcurrentTaskExecution = true;
Console.OutputEncoding = System.Text.Encoding.UTF8;
InitializeComponent();
webBrowser.Address = AppDomain.CurrentDomain.BaseDirectory+@"index.html";
webBrowser.JavascriptObjectRepository.Settings.LegacyBindingEnabled = true;
webBrowser.JavascriptObjectRepository.Register("JsObj", new JsObj(), BindingOptions.DefaultBinder);
public class JsObj
{
string message = string.Empty;
public async Task showMessageAsync()
{
await Task.Run(() =>
{
MessageBox.Show("this in C#." + message);
});
}
public void setMessageSync(string _message)
{
message = _message;
}
public async Task setMessageAsync(string _message)
{
await Task.Run(() =>
{
message = _message;
});
}
public async Task<string> getMessageAsync()
{
return await Task.Run(() =>
{
return message;
});
}
public async Task<string> getCurrTimeAsync()
{
return await Task.Run(() =>
{
return DateTime.Now.ToString("G");
});
}
}
4.指定CefSharp.BrowserSubprocess.exe目录
CefSettings settings = new CefSettings
{
Locale = "zh-CN",
BrowserSubprocessPath = "D:\\native\\CefSharp.BrowserSubprocess.exe",
};
Cef.Initialize(settings);