[摘录] WebView2 与 JS 交互
https://docs.microsoft.com/zh-cn/microsoft-edge/webview2/gettingstarted/win32
步骤 5-脚本
托管应用还可以将 JavaScript 插入 Web 视图。 你可以通过任务 Web 视图执行任意 JavaScript 或添加初始化脚本。 已添加的初始化脚本将应用于所有未来的顶级文档和子框架导航,直到被删除,并在创建全局对象之后以及执行 HTML 文档包括的任何其他脚本之前运行。
复制以下代码片段并粘贴到其中 HelloWebView.cpp 。
// 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 时,将发生以下步骤。
- 主机注册处理程序以返回收到的消息,返回到 web 内容
- 主机将向注册处理程序的 web 内容插入脚本,以便从主机打印消息
- 主机为将 URL 发布到主机的 web 内容插入脚本
- 将触发主机的处理程序,并将消息 \ (URL \)返回到 web 内容
- 将触发 web 内容的处理程序,并通过主机 \ (URL \)打印消息
复制以下代码片段并粘贴到其中 HelloWebView.cpp 。
// 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.
// 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,
- the host registers a handler to return received message back to the web content
- the host injects a script to the web content that registers a handler to print message from the host
- the host injects a script to the web content that posts the URL to the host
- the host's handler is triggered and returns the message (the URL) to the web content
- 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,
// 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 交互的更多相关文章
- 关于JS交互--调用h5页面,点击页面的按钮,分享到微信朋友圈,好友
关于js交互,在iOS中自然就想到了调用代理方法 另外就是下面的,直接上代码了: 如果你的后台需要知道你的分享结果,那么,就在回调里面调用上传到服务器结果的请求即可
- webView和js交互
与 js 交互 OC 调用 JS // 执行 js - (void)webViewDidFinishLoad:(UIWebView *)webView { NSString *title = [web ...
- 李洪强iOS经典面试题147-WebView与JS交互
李洪强iOS经典面试题147-WebView与JS交互 WebView与JS交互 iOS中调用HTML 1. 加载网页 NSURL *url = [[NSBundle mainBundle] UR ...
- WebView---Android与js交互实例
Android 中可以通过webview来实现和js的交互,在程序中调用js代码,只需要将webview控件的支持js的属性设置为true 原文地址:http://blog.csdn.net/it10 ...
- iOS与JS交互实战篇(ObjC版)
前言 ObjectiveC与Js交互是常见的需求,可对于新手或者所谓的高手而言,其实并不是那么简单明了.这里只介绍iOS7.0后出来的JavaScriptCore framework. 关于JavaS ...
- Android WebView加载本地html并实现Java与JS交互
最近做的一个项目中,用到自定义地图,将自定义地图转换成html页面,现在需要做的是如何将本地的html加载到android中,并可以实现交互. 相关讲解: 其实webview加载资源的速度并不慢,但是 ...
- WinForm程序执行JS代码的多种方法以及使用WebBrowser与JS交互
方法一 使用微软官方组件Interop.MSScriptControl 1.msscript.ocx下载的地址 http://www.microsoft.com/downloads/details ...
- WKWebView新特性及JS交互
引言 一直听说WKWebView比UIWebView强大许多,可是一直没有使用到,今天花了点时间看写了个例子,对其API的使用有所了解,为了日后能少走弯路,也为了让大家更容易学习上手,这里写下这篇文章 ...
- 【转】第7篇:Xilium CefGlue 关于 CLR Object 与 JS 交互类库封装报告:全自动注册与反射方法分析
作者: 牛A与牛C之间 时间: 2013-12-12 分类: 技术文章 | 2条评论 | 编辑文章 主页 » 技术文章 » 第7篇:Xilium CefGlue 关于 CLR Object 与 JS ...
- 【转】第6篇:Xilium CefGlue 关于 CLR Object 与 JS 交互类库封装报告:自动注册JS脚本+自动反射方法分析
作者: 牛A与牛C之间 时间: 2013-11-21 分类: 技术文章 | 暂无评论 | 编辑文章 主页 » 技术文章 » 第6篇:Xilium CefGlue 关于 CLR Object 与 JS ...
随机推荐
- python对象之间的交互
python对象之间的交互 先看看一般的类定义如下: class 类名: def __init__(self,参数1,参数2): self.对象的属性1 = 参数1 self.对象的属性2 = 参数2 ...
- 测试工程师-年终总结PPT
2022年年终总结-xxx 一.首页 2022年年终总结暨2023年工作计划 汇报人:测试组-xxx 日期: 2023.1.13 二.目录 1.年度工作概述 2.工作亮点展示 3.持续精进点 4.明年 ...
- BI 工具助力企业解锁数字化工厂,开启工业智能新视界
背景 在 2022 年公布的<"十四五"数字经济发展规划>中,政府不断增加对制造业数字化转型的政策支持力度,积极倡导制造企业采用最新技术,提升自动化.数字化和智能化水平 ...
- 【Maxwell】01 安装及入门
官网地址: https://maxwells-daemon.io/ 下载地址(版本发行): https://github.com/zendesk/maxwell/releases 参考教程自尚硅谷视频 ...
- 【Vue】Re17 Router 第四部分(参数传递,守卫函数)
一.案例搭建 新建Profile组件 组件写好内容后配置路由 { path : '/profile', component : () => import('../components/Profi ...
- (计算机类)人工智能方向会议的截止时间表 —— AI Conference Deadlines —— 会议投稿截止时间
由 https://paperswithcode.com/ 提供的时间表. 做AI方向的research,经常需要关注的就是conference的deadline,之前往往都是需要手动的去挨个搜索,下 ...
- 最小二乘法的矩阵正则化改进——“岭回归”和“LASSO回归”算法
看代码过程中发现了一个很奇怪的概念,叫做"最小二乘法的矩阵正则化",这个词汇十分的陌生,虽然最小二乘法是知道的,但是用了矩阵正则化的最小二乘法是个什么东西呢? 相关代码见: 强化学 ...
- 使用pybind11为Python编写一个简单的C语言扩展模块
相关: 为Python编写一个简单的C语言扩展模块 在Pybind11 出现之前为Python编写扩展模块的方法有多种,但是并没有哪种方法被认为一定比其他的好,因此也就变得在为Python编写扩展模块 ...
- 微服务全链路跟踪:jaeger集成hystrix
微服务全链路跟踪:grpc集成zipkin 微服务全链路跟踪:grpc集成jaeger 微服务全链路跟踪:springcloud集成jaeger 微服务全链路跟踪:jaeger集成istio,并兼容u ...
- shell脚本中$0 $1 $# $@ $* $? $$ 的各种符号意义详解
一.概述 shell中有两类字符:普通字符.元字符. 1. 普通字符 在Shell中除了本身的字面意思外没有其他特殊意义,即普通纯文本: 2. 元字符 是Shell的保留字符,在Shell中有着特殊的 ...