windows mfc webview2 接收html信息

news2024/9/30 17:24:43

webview2导入到mfc参考:

windows vs2022 MFC使用webview2嵌入网页-CSDN博客

webview2与js交互参考:WebView2教程(基于C++)【四】JS与C++互访(上)_window.chrome.webview.postmessage-CSDN博客

一、JS端发送和接收

JS中,通过postMessage方法向C++发送消息,代码如下

window.chrome.webview.postMessage(window.document.URL)

JS监听从C++发来的数据,代码如下:

window.chrome.webview.addEventListener("message", (e) => {
	//console.log(e);
	alert(e.data);
})

完整html:

<!DOCTYPE html>
<html>
	<head>
	</head>
	
	<body>
		<button onclick="test()">测试</button>
		<script>
			function test(){
				window.chrome.webview.postMessage('123')	
			}
			window.chrome.webview.addEventListener("message", (e) => {
				//console.log(e);
				alert(e.data);
			})
		</script>
	</body>
</html>

二、C++端webview2 接收消息和发送消息

C++中要想接收消息,必须注册一个WebMessageReceived事件,

在WebView2控件成功添加到窗口上时,我们就可以注册事件了,代码如下:

webview->add_WebMessageReceived(Callback<ICoreWebView2WebMessageReceivedEventHandler>(
				[](ICoreWebView2* webview, ICoreWebView2WebMessageReceivedEventArgs* args) -> HRESULT {
					wil::unique_cotaskmem_string message;
					args->TryGetWebMessageAsString(&message);//从html接收数据
					// processMessage(&message);
					webview->PostWebMessageAsString(message.get());//发送数据到html
					return S_OK;
				}).Get(), &token);

三、从本地加载一个html

本地文件路径:file:///C:/Users/76211/Desktop/a.html

完整代码:

void CMFCApplication1Dlg::LoadUrl(const wstring& strUrl)
{
	HWND hWnd = this->m_hWnd;

	// TODO:  在此添加您专用的创建代码
	// <-- WebView2 sample code starts here -->
	// Step 3 - Create a single WebView within the parent window
	// Locate the browser and set up the environment for WebView
	CreateCoreWebView2EnvironmentWithOptions(nullptr, nullptr, nullptr,
		Callback<ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler>(
			[hWnd, strUrl](HRESULT result, ICoreWebView2Environment* env) -> HRESULT {

				// Create a CoreWebView2Controller and get the associated CoreWebView2 whose parent is the main window hWnd
				env->CreateCoreWebView2Controller(hWnd, Callback<ICoreWebView2CreateCoreWebView2ControllerCompletedHandler>(
					[hWnd, strUrl](HRESULT result, ICoreWebView2Controller* controller) -> HRESULT {
						if (controller != nullptr) {
							webviewController = controller;
							webviewController->get_CoreWebView2(&webview);
						}

						// Add a few settings for the webview
						// The demo step is redundant since the values are the default settings
						wil::com_ptr<ICoreWebView2Settings> settings;
						webview->get_Settings(&settings);
						settings->put_IsScriptEnabled(TRUE);
						settings->put_AreDefaultScriptDialogsEnabled(TRUE);
						settings->put_IsWebMessageEnabled(TRUE);

						// Resize WebView to fit the bounds of the parent window
						RECT bounds;
						::GetClientRect(hWnd, &bounds);
						webviewController->put_Bounds(bounds);

						// Schedule an async task to navigate to Bing
						webview->Navigate(strUrl.c_str());

						// <NavigationEvents>
						// Step 4 - Navigation events
						// register an ICoreWebView2NavigationStartingEventHandler to cancel any non-https navigation
						EventRegistrationToken token;
						webview->add_NavigationStarting(Callback<ICoreWebView2NavigationStartingEventHandler>(
							[](ICoreWebView2* webview, ICoreWebView2NavigationStartingEventArgs* args) -> HRESULT {
								wil::unique_cotaskmem_string uri;
								args->get_Uri(&uri);
								std::wstring source(uri.get());
								/*if (source.substr(0, 5) != L"https") {
									args->put_Cancel(true);
								}*/
								return S_OK;
							}).Get(), &token);
						// </NavigationEvents>

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

						// <CommunicationHostWeb>
						// Step 6 - Communication between host and web content
						// Set an event handler for the host to return received message back to the web content
						webview->add_WebMessageReceived(Callback<ICoreWebView2WebMessageReceivedEventHandler>(
							[](ICoreWebView2* webview, ICoreWebView2WebMessageReceivedEventArgs* args) -> HRESULT {
								wil::unique_cotaskmem_string message;
								args->TryGetWebMessageAsString(&message);//从html接收数据
								// processMessage(&message);
								webview->PostWebMessageAsString(message.get());//发送数据到html
								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
						webview->AddScriptToExecuteOnDocumentCreated(
							L"window.chrome.webview.addEventListener(\'message\', event => alert(event.data));" \
							L"window.chrome.webview.postMessage(window.document.URL);",
							nullptr);
						// </CommunicationHostWeb>

						return S_OK;
					}).Get());
				return S_OK;
			}).Get());
}

四、运行截图

打开界面,本地网页在mfc界面中:

从html接收到的数据:

 发送到html的数据:

五、微软官方参考

WebView2 功能和 API 概述 - Microsoft Edge Developer documentation | Microsoft Learn

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2066146.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

12代装win7影响性能吗?12代酷睿装win7关闭小核提高性能方法

12代酷睿装win7影响性能吗&#xff1f;12代酷睿装win7在性能上有点损耗&#xff0c;可以关闭小核提高性能。有些小朋友不知道怎么关闭上核来提高性能&#xff0c;下面电脑系统城小编就教大家12代酷睿装win7关闭核提高性能方法。 12代酷睿装win7说明&#xff1a;关闭小核解锁更多…

【分布式】分布式Session共享

这里通过SpringSession来实现Session的共享&#xff0c;Session数据存储在Redis中 SpringSession的操作指南&#xff1a; https://docs.spring.io/spring-session/docs/2.5.6/reference/html5/guides/boot-redis.html 导入相关的依赖 <dependency><groupId>org.s…

算法入门-递归3

第四部分&#xff1a;递归 143.重排链表&#xff08;中等&#xff09; 题目&#xff1a;给定一个单链表 L 的头节点 head &#xff0c;单链表 L 表示为&#xff1a; L0 → L1 → … → Ln - 1 → Ln 请将其重新排列后变为&#xff1a; L0 → Ln → L1 → Ln - 1 → L2 → …

问题-小技巧-win11状态栏卡住

目前我只知道治标不治本的办法&#xff0c;打开任务管理器&#xff0c;找到Windows资源管理器右键重新启动&#xff0c;就可以解决这个问题。 这个问题我觉得是Win11自己的问题&#xff0c;等有新的发现&#xff0c;会进行补充。

使用Hutool工具类轻松生成验证码

效果图&#xff1a; 引入依赖&#xff1a; <!--hutool工具包--> <dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.7.15</version> </dependency>核心代码 import cn.hutool.…

使用docker-compose运行kafka及验证(无需zookpeer)

前言&#xff1a;要求安装docker-compose kafka镜像版本&#xff1a;apache/kafka:3.8.0 可能存在镜像拉不下来的情况&#xff1a; 1、vim /etc/docker/daemon.json {"data-root":"/data/docker","registry-mirrors": ["https://docker.m…

高性价比百元蓝牙耳机如何选择?四款首选高性价比蓝牙耳机推荐

不知道什么时候开始&#xff0c;有线耳机悄悄的淡出了我们的视线。现在几乎都是蓝牙耳机首当前冲&#xff0c;因为比起有线耳机&#xff0c;蓝牙耳机更携带方便&#xff0c;拿出来就是秒连&#xff0c;体验感也不差。而且随着蓝牙耳机的价格不断下降&#xff0c;同时&#xff0…

【图文并茂】ant design pro 如何优雅奇妙地添加修改密码的功能

如上图所示&#xff0c;我们要加这样的一个功能&#xff0c;如何做呢&#xff1f; 首先要写好前端页面&#xff0c;再对接好后端&#xff0c;然后我们要判断当前密码是否正确&#xff0c;如果正确才能新密码修改好。 前端页面 src/pages/account/change-password/index.tsx …

【直观表格】常见神经网络计算复杂度对比 ——从时间复杂度和空间复杂度角度剖析

常见神经网络计算复杂度对比 ——从时间复杂度和空间复杂度角度剖析 【表格】常见神经网络计算复杂度对比 神经网络类型时间复杂度空间复杂度关键参数备注多层感知机&#xff08;MLP&#xff09; O ( n ⋅ d ⋅ h ) O(n \cdot d \cdot h) O(n⋅d⋅h) O ( d ⋅ h h ) O(d \c…

helm安装jenkins保姆级别

一、创建nfs服务器 这一步跳过、自行百度 注意&#xff1a;要给共享目录赋予权限chmod一下&#xff0c;不然到时候容器没办法在目录里面创建文件&#xff0c;初始化时候会报错误代码2 二、添加Jenkins的Helm仓库 helm repo add jenkinsci https://charts.jenkins.io helm re…

护眼台灯真的有用吗?学生护眼台灯十大牌子推荐

在当前近视患者剧增&#xff0c;我们发现近视还与青光眼的发生有关联&#xff0c;这是一种可能导致永久性视力丧失的眼病。青光眼通常是由于眼内压力过高造成的视神经损伤。高度近视患者的眼球结构变化可能增加眼压&#xff0c;从而提高患青光眼的风险。预防近视变得非常重要&a…

html js弹幕功能

效果如上 html <!DOCTYPE html> <html><head><meta charset"utf-8" /><title></title><script charset"utf-8" src"https://unpkg.com/vue2.6.14/dist/vue.min.js" type"text/javascript">…

[C语言]-基础知识点梳理-编译、链接、预处理

前言 各位师傅大家好&#xff0c;我是qmx_07,今天来给大家讲解以下程序运行会经历哪些事情 翻译环境和运⾏环境 在ANSIC的任何⼀种实现中&#xff0c;存在两个不同的环境 第1种是翻译环境&#xff0c;在这个环境中源代码被转换为可执⾏的机器指令&#xff08;⼆进制指令&a…

[FSCTF 2023]ez_php2

[FSCTF 2023]ez_php2 点开之后是一段php代码&#xff1a; <?php highlight_file(__file__); Class Rd{public $ending;public $cl;public $poc;public function __destruct(){echo "All matters have concluded";die($this->ending);}public function __call…

django宿舍管理系统 ---附源码98595

目 录 摘要 1 绪论 1.1 研究背景与意义 1.2 国内外研究现状 1.3论文结构与章节安排 2 宿舍管理系统系统分析 2.1 可行性分析 2.2 系统流程分析 2.2.1 数据增加流程 2.2.2 数据修改流程 2.2.3 数据删除流程 2.3 系统功能分析 2.3.1 功能性分析 2.3.2 非功能性分析…

vue vite创建项目步骤

1. 创建vue项目 node版本需18以上 不然报错 npm init vuelatest2. 项目配置 配置项目的icon配置项目的标题配置jsconfig.json 3. 项目目录结构划分 4.css样式的重置 npm install normalize.cssreset.css html {line-height: 1.2; }body, h1, h2, h3, h4, ul, li {padding…

aspose-words将tinymce中的换页符转换为word的换页符

aspose-words版本&#xff1a;21.1 java&#xff1a;1.8 tinymc&#xff1a;5.0.16 public void convertPageBreak() throws Exception{String sourceHtml "hello<!-- pagebreak -->world";sourceHtml sourceHtml.replaceAll("<!-- pagebreak -->…

鸿蒙崛起,前端/Java人才如何搭上这趟技术快车?

在科技飞速发展的今天&#xff0c;鸿蒙系统的崛起犹如一颗璀璨的新星&#xff0c;照亮了技术领域的新航道。对于前端和 Java 人才来说&#xff0c;这不仅仅是一个新的挑战&#xff0c;更是一次搭乘技术快车、实现职业飞跃的绝佳机遇。 一、鸿蒙崛起之势 鸿蒙系统自诞生以来&…

开放式耳机是什么意思?开放式对比入耳式耳机的音质更通透

开放式耳机是一种无需入耳的蓝牙耳机。它主要提供的是一种自然、开放的音频体验&#xff0c;并且无需封耳&#xff0c;能维持佩戴者对外界的感知和环境的联系。这种耳机并不需要深入耳道&#xff0c;但又能清晰听清耳机传来的内容&#xff0c;所以在佩戴方面会更加舒适。 开放…

告别本地硬件烦恼,一分钟教你用云端部署玩Stable Diffusion!

Stable diffusion有两种部署方式&#xff0c;分别是本地部署和云端部署。 本地部署需要把程序安装到自己的电脑上&#xff0c;因此对设备&#xff08;尤其是显卡显存&#xff09;要求比较高&#xff0c;但很多小伙伴反映自己设备不到位&#xff0c;升级设备费用成本过高&#…