参考了https://blog.csdn.net/CAir2/article/details/91576805这篇博客
继承v8的Execute函数,
```bool ClientV8ExtensionHandler::Execute(const CefString& func_name,
CefRefPtr<CefV8Value> object,
const CefV8ValueList& arguments,
CefRefPtr<CefV8Value>& retval,
CefString& exception)
{
if (func_name == L"register")
{
if (arguments.size() == 1 && arguments[0]->IsFunction())
{
CefRefPtr<CefV8Context> context = CefV8Context::GetCurrentContext();
CefRefPtr<CefV8Value> call_back = arguments[0];
//由于这里只是一个demo,所以把funcid固定为1,如果存在多个注册回调函数,请维护funcid和callback的关系
//if (m_render_app)
// m_render_app->AddCallBack(1, context, call_back);
//调用回调,进入上下文
context->Enter();
CefV8ValueList call_arguments;
call_arguments.push_back(CefV8Value::CreateString(_T("hellow word")));
//调用回调函数,回调参数
call_back->ExecuteFunction(NULL, call_arguments);
//退出上下文
context->Exit();
return true;
}
}
else if (func_name == L"ReadID")
{
if (arguments.size() == 1 && arguments[0]->IsFunction())
{
CPublic::ReadID_context = CefV8Context::GetCurrentContext();//保存context
CPublic::browser = CPublic::ReadID_context->GetBrowser();//保存call_back
CPublic::ReadID_call_back = arguments[0];
HWND hwnd = AfxGetApp()->GetMainWnd()->GetSafeHwnd();
::PostMessage(hwnd, WM_MYMSGReadID, 0, 0);//发送消息到主窗口执行消息函数
return true;
}
else
{
return false;
}
}
调用的消息函数
LRESULT CMFCApplication1Dlg::OnMyMsgReadID(WPARAM H, LPARAM J)
{
//CPublic::ReadID_context->GetBrowser() = CPublic::browser;
//CefRefPtr<CefBrowser> browser = CPublic::ReadID_context->GetBrowser();
if (CPublic::ReadID_context&&CPublic::ReadID_call_back)
{
CPublic::ReadID_context->Enter();//一定要先Enter
if (CPublic::ReadID_context->GetBrowser()) //判断上下文中的Browser是否存在
{
////处理任务,并且执行回调
CefV8ValueList call_arguments;
call_arguments.push_back(CefV8Value::CreateString(_T("123456")));
CPublic::ReadID_call_back->ExecuteFunctionWithContext(NULL,NULL, call_arguments);
}
CPublic::ReadID_context->Exit();//退出Context
//m_CallBackMap.erase(callbackId);
}
return 0;
}
注册的回调方法
void CCefBrowserApp::OnWebKitInitialized()
{
std::string extensionCode =
"var g_value=\"global value here\";"
"var MyMath;"
"if (!MyMath)"
" MyMath = {};"
"(function() {"
" MyMath.register = function(call_back) {"
" native function register(call_back);"
" return register(call_back);"
" MyMath.hellow = 'Hello JS!';"//定义一个MyMath的成员变量"
" };"
" MyMath.ReadID = function(call_back) {"
" native function ReadID(call_back);"
" return ReadID(call_back);"
" };"
"})();";
CefRefPtr<CefV8Handler> handler = new ClientV8ExtensionHandler();
// Register the extension.
CefRegisterExtension("v8/test", extensionCode, handler);
}