How to Add a new native class to WebWorker's context in JavaScriptCore?
JavascriptWebkitCustomizationWeb WorkerJavascriptcoreJavascript Problem Overview
I have an application that extends JavaScript via JavaScriptCore, in a webkit-gtk browser. Right now I have several classes that I add to the global context like so:
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);
}
Now, I'd like to also add those classes to the WebWorker's context, so I can call them from workers instantiated in JS.
I've tried getting the Worker
object like so:
JSStringRef workerStr = JSStringCreateWithUTF8CString("Worker");
JSObjectRef worker = JSObjectGetProperty(context, globalObj, workerStr, NULL);
JSObjectSetProperty(context, worker, str, classObj, kJSPropertyAttributeNone, NULL);
JSStringRelease(workerStr);
But that adds it to the WorkerConstructor
object, and when a new Worker()
is called, the classes are not available.
Javascript Solutions
Solution 1 - Javascript
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
Solution 2 - Javascript
Use "importScripts()" to share the resources with the WorkerGlobalScope
importScripts('resource.js');