CEF JS调用C++代码

时间:2022-09-22 09:12:19

CEF JS调用C++代码

flyfish

CEF supports the creation of JS functions with native implementations. Functions are created using the CefV8Value::CreateFunction() static method that accepts name and CefV8Handler arguments. Functions can only be created and used from within a context .

CEF3支持本地实现JS函数的创建,函数使用静态方法CefV8Value::CreateFunction() 创建。接收name和CefV8Handler参数。函数仅能在context中创建和使用。

An implementation of the CefV8Handler interface that must be provided by the client application
本地应用程序必须提供的CefV8Handler接口的实现

代码如下

#pragma once
#include "include/cef_v8.h"
class MyV8Handler :
public CefV8Handler
{
public:
MyV8Handler();
~MyV8Handler();

virtual bool Execute(const CefString& name,
CefRefPtr<CefV8Value> object,
const CefV8ValueList& arguments,
CefRefPtr<CefV8Value>& retval,
CefString& exception)
override;


IMPLEMENT_REFCOUNTING(MyV8Handler);
};
#include "stdafx.h"
#include "MyV8Handler.h"


MyV8Handler::MyV8Handler()
{
}


MyV8Handler::~MyV8Handler()
{
}
bool MyV8Handler::Execute(const CefString& name,
CefRefPtr<CefV8Value> object,
const CefV8ValueList& arguments,
CefRefPtr<CefV8Value>& retval,
CefString& exception)
{


if (name == "JSFunction")
{
if (arguments.size() == 2)
{
CefString A = arguments.at(0)->GetStringValue();
CefString B = arguments.at(1)->GetStringValue();

TCHAR szT[256] = { 0 };
_stprintf_s(szT, 256, _T("A = %s, B = %s\r\n"), A.c_str(), B.c_str());
AfxMessageBox(szT);
retval = CefV8Value::CreateInt(0);
return true;
}
}

// Function does not exist.
return false;
}

帮助文档是重新写了一个类MyRenderProcessHandler 继承自CefRenderProcessHandler
这里是在原来的ClientApp类中增加基类CefRenderProcessHandler。

class ClientApp: public CefApp,
public CefBrowserProcessHandler, public CefRenderProcessHandler

ClientApp类的头文件增加

    void OnContextCreated(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
CefRefPtr<CefV8Context> context);
void OnWebKitInitialized() override;// Called after WebKit has been initialized.
CefRefPtr<CefRenderProcessHandler> GetRenderProcessHandler()
{
return this;
}

实现文件

void ClientApp::OnContextCreated(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
CefRefPtr<CefV8Context> context)
{

CefRefPtr<CefV8Value> object = context->GetGlobal();
CefRefPtr<CefV8Value> func = CefV8Value::CreateFunction("JSFunction", new MyV8Handler);
object->SetValue("JSFunction", func, V8_PROPERTY_ATTRIBUTE_NONE);
}

void ClientApp::OnWebKitInitialized()
{
}

测试使用代码

CefRefPtr<CefBrowser> browser=m_cefHandler->GetBrowser();
browser->GetMainFrame()->LoadURL();

HTML样本

<html>
<head>
</head>
<body>
<script type="text/javascript">
function Test(){
window.JSFunction(document.getElementById("A").value, document.getElementById("B").value);
}
</script>
<form>
A: <input type="text" id="A" />B:
<input type="text" id="B" /><input type="button" value="Test" onclick="Test()"/>
</form>
</html>