https://docs.microsoft.com/zh-cn/microsoft-edge/webview2/gettingstarted/win32

步骤 5-脚本

托管应用还可以将 JavaScript 插入 Web 视图。 你可以通过任务 Web 视图执行任意 JavaScript 或添加初始化脚本。 已添加的初始化脚本将应用于所有未来的顶级文档和子框架导航,直到被删除,并在创建全局对象之后以及执行 HTML 文档包括的任何其他脚本之前运行。

复制以下代码片段并粘贴到其中 HelloWebView.cpp

C++
// Schedule an async task to add initialization script that freezes the Object object
webviewWindow->AddScriptToExecuteOnDocumentCreated(L"Object.freeze(Object);", nullptr);
// Schedule an async task to get the document URL
webviewWindow->ExecuteScript(L"window.document.URL;", Callback<ICoreWebView2ExecuteScriptCompletedHandler>(
[](HRESULT errorCode, LPCWSTR resultObjectAsJson) -> HRESULT {
LPCWSTR URL = resultObjectAsJson;
//doSomethingWithURL(URL);
return S_OK;
}).Get());

现在,Web 视图应该始终冻结 Object 对象并返回页面文档一次。

备注

脚本注入 Api \ (以及某些其他 WebView2 Api \)是异步的,如果必须按特定顺序运行代码,则应使用回调。

步骤 6-主机和 web 内容之间的通信

宿主和 web 内容也可能通过该方法互相通信 postMessage 。 在 web 视图内运行的 web 内容可能会通过该方法向主机发布 window.chrome.webview.postMessage ,并且消息由主机上任何注册的 ICoreWebView2WebMessageReceivedEventHandler 事件处理程序处理。 同样,主机可以通过 " ICoreWebView2::PostWebMessageAsString 或" ICoreWebView2::PostWebMessageAsJSON 方法处理 web 内容,这由从侦听器添加的处理程序捕获 window.chrome.webview.addEventListener 。 通信机制允许 web 内容通过将消息传递给请求主机调用本机 Api 来利用本机功能。

作为了解机制的示例,当你尝试在 Web 视图中打印文档 URL 时,将发生以下步骤。

  1. 主机注册处理程序以返回收到的消息,返回到 web 内容
  2. 主机将向注册处理程序的 web 内容插入脚本,以便从主机打印消息
  3. 主机为将 URL 发布到主机的 web 内容插入脚本
  4. 将触发主机的处理程序,并将消息 \ (URL \)返回到 web 内容
  5. 将触发 web 内容的处理程序,并通过主机 \ (URL \)打印消息

复制以下代码片段并粘贴到其中 HelloWebView.cpp

C++
// Set an event handler for the host to return received message back to the web content
webviewWindow->add_WebMessageReceived(Callback<ICoreWebView2WebMessageReceivedEventHandler>(
[](ICoreWebView2* webview, ICoreWebView2WebMessageReceivedEventArgs * args) -> HRESULT {
PWSTR message;
args->TryGetWebMessageAsString(&message);
// processMessage(&message);
webview->PostWebMessageAsString(message);
CoTaskMemFree(message);
return S_OK;
}).Get(), &token); // Schedule an async task to add initialization script that
// 1) Add an listener to print message from the host
// 2) Post document URL to the host
webviewWindow->AddScriptToExecuteOnDocumentCreated(
L"window.chrome.webview.addEventListener(\'message\', event => alert(event.data));" \
L"window.chrome.webview.postMessage(window.document.URL);",
nullptr);

https://docs.microsoft.com/en-us/microsoft-edge/hosting/webview2/gettingstarted

Step 5 - Scripting

The hosting app can also inject JavaScript into WebView. You can task WebView to execute arbitrary JavaScript or add initialization scripts. Added initialization scripts apply to all future top level document and child frame navigation until removed, and run after the global object has been created and before any other script included by the HTML document is executed.

Copy the following code below // Step 5 - Scripting.

C++
// Schedule an async task to add initialization script that freezes the Object object
webviewWindow->AddScriptToExecuteOnDocumentCreated(L"Object.freeze(Object);", nullptr);
// Schedule an async task to get the document URL
webviewWindow->ExecuteScript(L"window.document.URL;", Callback<ICoreWebView2ExecuteScriptCompletedHandler>(
[](HRESULT errorCode, LPCWSTR resultObjectAsJson) -> HRESULT {
LPCWSTR URL = resultObjectAsJson;
//doSomethingWithURL(URL);
return S_OK;
}).Get());

Now WebView will always freeze the Object object and return the page document once.

Note that these script injection APIs (and some other WebView2 APIs) are asynchronous, you should use callbacks if code is to be executed in a particular order.

Step 6 - Communication between host and web content

The host and the web content can also communicate with each other through postMessage. The web content running within a WebView can post to the host through window.chrome.webview.postMessage, and the message would be handled by any registered ICoreWebView2WebMessageReceivedEventHandler on the host. Likewise, the host can message the web content through ICoreWebView2::PostWebMessageAsString or ICoreWebView2::PostWebMessageAsJSON, which would be caught by handlers added from window.chrome.webview.addEventListener. The communication mechanism allows the web content to utilize native capabilities by passing messages to ask the host to call native APIs.

As an example to understand the mechanism, let's try printing out the document URL in WebView with a little detour,

  1. the host registers a handler to return received message back to the web content
  2. the host injects a script to the web content that registers a handler to print message from the host
  3. the host injects a script to the web content that posts the URL to the host
  4. the host's handler is triggered and returns the message (the URL) to the web content
  5. the web content's handler is triggered and prints the host's message (the URL)

Copy the following code below // Step 6 - Communication between host and web content,

C++
// Set an event handler for the host to return received message back to the web content
webviewWindow->add_WebMessageReceived(Callback<ICoreWebView2WebMessageReceivedEventHandler>(
[](ICoreWebView2* webview, ICoreWebView2WebMessageReceivedEventArgs * args) -> HRESULT {
PWSTR message;
args->TryGetWebMessageAsString(&message);
// processMessage(&message);
webview->PostWebMessageAsString(message);
CoTaskMemFree(message);
return S_OK;
}).Get(), &token); // Schedule an async task to add initialization script that
// 1) Add an listener to print message from the host
// 2) Post document URL to the host
webviewWindow->AddScriptToExecuteOnDocumentCreated(
L"window.chrome.webview.addEventListener(\'message\', event => alert(event.data));" \
L"window.chrome.webview.postMessage(window.document.URL);",
nullptr);

[摘录] WebView2 与 JS 交互的更多相关文章

  1. 关于JS交互--调用h5页面,点击页面的按钮,分享到微信朋友圈,好友

    关于js交互,在iOS中自然就想到了调用代理方法 另外就是下面的,直接上代码了: 如果你的后台需要知道你的分享结果,那么,就在回调里面调用上传到服务器结果的请求即可

  2. webView和js交互

    与 js 交互 OC 调用 JS // 执行 js - (void)webViewDidFinishLoad:(UIWebView *)webView { NSString *title = [web ...

  3. 李洪强iOS经典面试题147-WebView与JS交互

    李洪强iOS经典面试题147-WebView与JS交互   WebView与JS交互 iOS中调用HTML 1. 加载网页 NSURL *url = [[NSBundle mainBundle] UR ...

  4. WebView---Android与js交互实例

    Android 中可以通过webview来实现和js的交互,在程序中调用js代码,只需要将webview控件的支持js的属性设置为true 原文地址:http://blog.csdn.net/it10 ...

  5. iOS与JS交互实战篇(ObjC版)

    前言 ObjectiveC与Js交互是常见的需求,可对于新手或者所谓的高手而言,其实并不是那么简单明了.这里只介绍iOS7.0后出来的JavaScriptCore framework. 关于JavaS ...

  6. Android WebView加载本地html并实现Java与JS交互

    最近做的一个项目中,用到自定义地图,将自定义地图转换成html页面,现在需要做的是如何将本地的html加载到android中,并可以实现交互. 相关讲解: 其实webview加载资源的速度并不慢,但是 ...

  7. WinForm程序执行JS代码的多种方法以及使用WebBrowser与JS交互

    方法一 使用微软官方组件Interop.MSScriptControl 1.msscript.ocx下载的地址   http://www.microsoft.com/downloads/details ...

  8. WKWebView新特性及JS交互

    引言 一直听说WKWebView比UIWebView强大许多,可是一直没有使用到,今天花了点时间看写了个例子,对其API的使用有所了解,为了日后能少走弯路,也为了让大家更容易学习上手,这里写下这篇文章 ...

  9. 【转】第7篇:Xilium CefGlue 关于 CLR Object 与 JS 交互类库封装报告:全自动注册与反射方法分析

    作者: 牛A与牛C之间 时间: 2013-12-12 分类: 技术文章 | 2条评论 | 编辑文章 主页 » 技术文章 » 第7篇:Xilium CefGlue 关于 CLR Object 与 JS ...

  10. 【转】第6篇:Xilium CefGlue 关于 CLR Object 与 JS 交互类库封装报告:自动注册JS脚本+自动反射方法分析

    作者: 牛A与牛C之间 时间: 2013-11-21 分类: 技术文章 | 暂无评论 | 编辑文章 主页 » 技术文章 » 第6篇:Xilium CefGlue 关于 CLR Object 与 JS ...

随机推荐

  1. 如何在AS中实现mysql查询并输出在视图上

    新建子线程启用mysql new Thread(){ @override public void run(){ //在这里进行数据库调用 } }.start(); handler简单使用方法 hand ...

  2. app专项测试:app弱网测试(测试工具)

    app专项测试:app弱网测试(测试工具) 除了常用的 fiddler,charles 可以模拟弱网,还有硬件工具弱网仪 HoloWAN也可以模拟弱网 使用弱网仪有以下优点:1.即插即用,无需调试和复 ...

  3. 【Mybatis-Plus】联表分页查询实现

    参考文章: https://blog.csdn.net/weixin_43847283/article/details/125822614 上上周写的SQL案例确实可以重构,所以搬到Demo里面测试看 ...

  4. 【Spring Data JPA】02 快速上手

    完成一个CRUD - 创建工程导入依赖坐标 - 配置Spring的配置文件 - 配置ORM的实体类,绑定映射关系 - 编写一个符合SpringDataJpa的dao接口 Maven依赖坐标 <p ...

  5. 【Docker】03 基础操作

    [Docker 本体操作相关] 检查Docker版本: docker -v 检查Docker当前状态: systemctl status docker 停止Docker与开启Docker system ...

  6. MyBatis-Plus删除操作的几种基本方法

    delete删除的三种方法 一.根据 id 删除 @Test void deleteById(Integer id) { empMapper.deleteById(new Emp().getId()) ...

  7. 深度学习需要float64精度吗 —— 为什么各大深度学习框架均不支持float64的深度学习运算呢 —— 商用NVIDIA显卡的float64性能是否多余呢

    首先要知道这么几个事实,也是交代一下本文要讨论的问题的背景: 各大深度学习框架均支持float64类型的简单运算,但是均不支持float64的深度学习的运算操作: 作为深度学习运行的加速设备,各种GP ...

  8. 对国产AI计算框架要有一定的包容力——记“mindspore”使用过程中的“不良反应”

    看mindspore的官方文档,居然有502错误,恶心到了: 打开Eager模式的链接,报错:

  9. 如何实现基于Cortex-A9 的UART裸机驱动

    前言 Uart在一个嵌入式系统中是一个非常重要的模块,他承担了CPU与用户交互的桥梁.用户输入信息给程序.CPU要打印一些信息给终端都要依赖UART. 本文将以Exynos4412的UART控制器为基 ...

  10. [深度学习] 时间序列分析工具TSLiB库使用指北

    TSLiB是一个为深度学习时间序列分析量身打造的开源仓库.它提供了多种深度时间序列模型的统一实现,方便研究人员评估现有模型或开发定制模型.TSLiB涵盖了长时预测(Long-term forecast ...