前言
前一篇文章介绍过CEF在WIN32程序中嵌入chrome内核浏览器的例子:http://blog.youkuaiyun.com/mfcing/article/details/43973377
这里介绍的是嵌入浏览器后,网页的JS脚本函数与C++代码的交互,这个很多地方都用得到。比如:音乐播放器里网页上的播放,客户端资源中心里的资源下载……
JS调用C++函数
首先需要重写CefRenderProcessHandler的OnContextCreated接口,为什么呢?学习CEF库的使用必须仔细阅读他的头文件里的注视部分:
// Called immediately after the V8 context for a frame has been created. To
// retrieve the JavaScript 'window' object use the CefV8Context::GetGlobal()
// method. V8 handles can only be accessed from the thread on which they are
// created. A task runner for posting tasks on the associated thread can be
// retrieved via the CefV8Context::GetTaskRunner() method.
///
/*--cef()--*/
virtual void OnContextCreated(CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
CefRefPtr<CefV8Context> context) {}
这个接口实在chrome的V8引擎创建后调用的,在这里我们需要将JS里面调用的函数和C++的执行函数关联起来,这样JS就可以“执行”C++代码了。
我们的函数都是定义在window对象中的(不知道JS中这个是不是叫对象),根据注视我们需要GetGlobal获取这个对象。
我的代码是这样的:
CefR