How to Add a new native class to WebWorker's context in JavaScriptCore?

JavascriptWebkitCustomizationWeb WorkerJavascriptcore

Javascript 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');

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPedro VanzellaView Question on Stackoverflow
Solution 1 - JavascriptjanniksView Answer on Stackoverflow
Solution 2 - JavascriptLucas TadeuView Answer on Stackoverflow