如何在 JavaScriptCore 中为 WebWorker 的上下文添加一个新的本机类?

我有一个通过 JavaScriptCore 在 webkit-gtk 浏览器中扩展 JavaScript 的应用程序。现在我有几个类添加到全局上下文中,如下所示:

void create_js(gpointer context, char* className, JSClassDefinition clasDefinition) {
JSClassRef classDef = JSClassCreate(&clasDefinition);
JSObjectRef classObj = JSObjectMake(context, classDef, context);
JSObjectRef globalObj = JSContextGetGlobalObject(context);
JSStringRef str = JSStringCreateWithUTF8CString(className);
JSObjectSetProperty(context, globalObj, str, classObj, kJSPropertyAttributeNone, NULL);
JSStringRelease(str);
}

现在,我还想将这些类添加到 WebWorker 的上下文中,这样我就可以从 JS 中实例化的 worker 中调用它们。

我试过这样得到 Worker对象:

JSStringRef workerStr = JSStringCreateWithUTF8CString("Worker");
JSObjectRef worker = JSObjectGetProperty(context, globalObj, workerStr, NULL);
JSObjectSetProperty(context, worker, str, classObj, kJSPropertyAttributeNone, NULL);
JSStringRelease(workerStr);

但是这会将它添加到 WorkerConstructor对象中,当调用 new Worker()时,这些类就不可用了。

2238 次浏览

There is no way to modify the WorkerGlobalScope or comparable scopes/contexts before a web worker is started in most common browser implementations. These scopes become available only to the web workers context as soon as this specific web worker is launched.

The only way to use shared methods is to define them in a separate shared file/resource and include them using importScripts()

self.importScripts('foo.js');
self.importScripts('foo.js', 'bar.js', ...);
importScripts('foo.js');
importScripts('foo.js', 'bar.js', ...);

Note: importScripts() and self.importScripts() are effectively equivalent — both represent importScripts() being called from inside the worker's inner scope.


Sources

Use "importScripts()" to share the resources with the WorkerGlobalScope

importScripts('resource.js');