Native code can execute JS functions by using the ExecuteFunction()
and ExecuteFunctionWithContext() methods. The ExecuteFunction() method
should only be used if V8 is already inside a context as described in
the “Working with Contexts” section. The ExecuteFunctionWithContext()
method allows the application to specify the context that will be
entered for execution.
本地代码可以通过ExecuteFunction()和ExecuteFunctionWithContext()执行JS函数。ExecuteFunction()方法只能在V8对象已经在一个context中时才能进行调用,ExecuteFunctionWithContext()允许程序指定context进入并且执行该函数。
https://bitbucket.org/chromiumembedded/cef/wiki/JavaScriptIntegration.md
套路:
(1)在 OnJSBinding()中创建一个"register"函数
void MyRenderProcessHandler::OnContextCreated(
CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
CefRefPtr<CefV8Context> context) {
// Retrieve the context's window object.
CefRefPtr<CefV8Value> object = context->GetGlobal();
CefRefPtr<CefV8Handler> handler = new MyV8Handler(this);
object->SetValue("register",
CefV8Value::CreateFunction("register", handler),
V8_PROPERTY_ATTRIBUTE_NONE);
}
(2)在MyV8Handler::Execute()的实现中对"register"的context和function保存引用
bool MyV8Handler::Execute(const CefString& name,
CefRefPtr<CefV8Value> object,
const CefV8ValueList& arguments,
CefRefPtr<CefV8Value>& retval,
CefString& exception) {
if (name == "register") {
if (arguments.size() == 1 && arguments[0]->IsFunction()) {
callback_func_ = arguments[0];
callback_context_ = CefV8Context::GetCurrentContext();
return true;
}
}
return false;
}
(3)通过JavaScript注册JS callback
<script language="JavaScript">
function myFunc() {
// do something in JS.
}
window.