您还需要在运行时告诉 WebKit/JavaScriptCore 您的绑定(这是除了与 filename_wrap.o 链接之外的)。
具体来说,您需要将它们绑定到全局 JavaScript 对象(以便根据您的 .js 示例进行调用)。 WebKit 窗口上的回调可用于及时引用全局 JavaScript 上下文,然后您可以将函数注册到其上。
适应这个example https://github.com/vrruiz/WebKit-JavaScriptCore-Extensions/blob/master/webkit-02.c#L87挂钩到window-object-cleared
信号代码可能类似于以下内容:
/* the window callback -
fired when the JavaScript window object has been cleared */
static void window_object_cleared_cb(WebKitWebView *web_view,
WebKitWebFrame *frame,
gpointer context,
gpointer window_object,
gpointer user_data)
{
/* Add your classes to JavaScriptCore */
example_init(context); // example_init generated by SWIG
}
/* ... and in your main application set up */
void yourmainfunc()
{
....
g_signal_connect (G_OBJECT (web_view), "window-object-cleared",
G_CALLBACK(window_object_cleared_cb), web_view);
webkit_web_view_load_uri (WEBKIT_WEB_VIEW (web_view), "file://filename.html");
...
}
根据您使用的 SWIG 分支,您可能需要生成example_init
自己运行(检查文件名.cxx);供参考的是初始化函数的作用注册包装的 C 函数 https://github.com/oliver----/swig-v8/blob/devel/Doc/Manual/Javascript.md#wrapper-functions在 SWIG 中看起来像:
int example_init(JSContextRef context) {
JSObjectRef global = JSContextGetGlobalObject(context);
...
jsc_registerFunction(context, global, "gcd", _wrap_gcd);
...
}
注意——SWIG 尚未正式支持 JavaScript;上述指的是使用正在进行的(非生产)SWIG 分支。
参考:
- SWIG-V8 source https://github.com/oliver----/swig-v8和它的JavaScript 文档 https://github.com/oliver----/swig-v8/blob/devel/Doc/Manual/Javascript.md#wrapper-functions
- swig-jscsource https://github.com/ashishs99/swig-jsc和它的example https://github.com/ashishs99/swig-jsc/blob/a15943ac/Examples/javascript/simple/runme.cxx#L95注册绑定
- SWIG JavaScriptCore GSoC 项目source https://github.com/Neha03/gsoc2012-javascript(2012 年 Google 编程之夏)
- Webkit:扩展 JavaScript 文章--tutorial http://rvr.typepad.com/wind/2011/10/webkit-extending-javascript-1.html / 示例代码 https://github.com/vrruiz/WebKit-JavaScriptCore-Extensions