一、环境搭建
1、教程:https://kefong.blog.csdn.net/article/details/119910984 2、源码:https://gitee.com/kefong/mfccef.git 以下所有工作,都是在以上源码基础上进行。
二、在browser中重写网页加载完毕执行方法 CefLoadHandler->OnLoadEnd
1、[CCefBrowserEventHandler.h] CCefHandler中增加继承CefLoadHandler
CCefBrowserEventHandler.h
public CefLoadHandler
2、绑定
CCefBrowserEventHandler.h
virtual CefRefPtr<CefLoadHandler> GetLoadHandler() override { return this; }
3、重写方法OnLoadEnd,发送消息给render
CCefBrowserEventHandler.h
void OnLoadEnd(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
int httpStatusCode);
cef_handler.cpp
void CCefBrowserEventHandler::OnLoadEnd(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
int httpStatusCode) {
CEF_REQUIRE_UI_THREAD();
CefRefPtr<CefProcessMessage> message = CefProcessMessage::Create(L"changedom");
frame->SendProcessMessage(PID_RENDERER, message);
}
知识点:
browser浏览器(显示网页内容的外部框);render网页(如:frame等网页内容)
三、render接收browser中的消息,并修改网页内容
1、在CCefBrowserApp.h中增加继承public CefRenderProcessHandler
virtual CefRefPtr<CefRenderProcessHandler> GetRenderProcessHandler() override {
return this;
}
2、实现OnProcessMessageReceived方法 CCefBrowserApp.h
virtual bool OnProcessMessageReceived(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
CefProcessId source_process,
CefRefPtr<CefProcessMessage> message) override;
CCefBrowserApp.cpp
bool CCefBrowserApp::OnProcessMessageReceived(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
CefProcessId source_process,
CefRefPtr<CefProcessMessage> message) {
DCHECK_EQ(source_process, PID_BROWSER);
CefString message_name = message->GetName();
MessageBox(NULL, L"123456", NULL, NULL);
if (message_name == CefString("changedom")) {
frame->VisitDOM(new MyDomVisitor());
CefString js = "alert('test');";
frame->ExecuteJavaScript(js, frame->GetURL(), 0);
}
return false;
}
说明:message_name == CefString(“changedom”)中的changedom必须与browser中的传值一模一样
3、创建网页内容修改类:MyDomVisitor MyDomVisitor.h
#pragma once
class MyDomVisitor :public CefDOMVisitor
{
public:
void Visit(CefRefPtr<CefDOMDocument> document) override;
void TestAccess(CefRefPtr<CefDOMDocument> document);
void TestModify(CefRefPtr<CefDOMDocument> document);
protected:
IMPLEMENT_REFCOUNTING(MyDomVisitor);
};
MyDomVisitor.cpp
#include "pch.h"
#include "include/cef_dom.h"
#include "MyDomVisitor.h"
void MyDomVisitor::Visit(CefRefPtr<CefDOMDocument> document) {
TestAccess(document);
TestModify(document);
}
void MyDomVisitor::TestAccess(CefRefPtr<CefDOMDocument> document) {
}
void MyDomVisitor::TestModify(CefRefPtr<CefDOMDocument> document) {
CefRefPtr<CefDOMNode> kw = document->GetElementById("kw");
if (kw.get()) {
kw->SetElementAttribute("value", "test");
}
}
四、最终效果
|