windows mfc webview2 接收html信息

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

说明:

复制代码
webview->AddScriptToExecuteOnDocumentCreated(
							L"window.chrome.webview.addEventListener(\'message\', event => alert(event.data));" \
							L"window.chrome.webview.postMessage(window.document.URL);",
							nullptr);

这段代码在切换网页时会弹框,可以不需要

相关推荐
码农新猿类2 小时前
服务器本地搭建
linux·网络·c++
GOTXX2 小时前
【Qt】Qt Creator开发基础:项目创建、界面解析与核心概念入门
开发语言·数据库·c++·qt·图形渲染·图形化界面·qt新手入门
徐行1103 小时前
C++核心机制-this 指针传递与内存布局分析
开发语言·c++
序属秋秋秋3 小时前
算法基础_数据结构【单链表 + 双链表 + 栈 + 队列 + 单调栈 + 单调队列】
c语言·数据结构·c++·算法
mldl_4 小时前
(个人题解)第十六届蓝桥杯大赛软件赛省赛C/C++ 研究生组
c语言·c++·蓝桥杯
一个小白14 小时前
C++ 用红黑树封装map/set
java·数据库·c++
Lenyiin4 小时前
《 C++ 点滴漫谈: 三十三 》当函数成为参数:解密 C++ 回调函数的全部姿势
c++·回调函数·lenyiin
埜玊5 小时前
C++之 多继承
c++
雯0609~5 小时前
html:文件上传-一次性可上传多个文件,将文件展示到页面(可删除
前端·html
天天扭码6 小时前
项目登录注册页面太丑?试试我“仿制”的丝滑页面(全源码可复制)
前端·css·html