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

2

102

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.

Remise answered 12/8, 2015 at 17:37 Comment(3)
Not sure about your requirement exactly. But i think we can include one script which does this in the worker file. like this. importScripts("globalWorker.js")Batsman
You are putting the Worker class to the global context, you should add them to the WebWorker's context not the main context because the two contexts are different.Templet
You're trying to add the new created class to Worker class definition. Normally you need to add your class to the Global object and to every Global Object within a new created JSVirtualMachine. Worker will create a new JSVirtualMachine with it's global context and global object; a totally seperated environementSelfassertion
G
1

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

Gliadin answered 29/8, 2018 at 8:12 Comment(0)
H
0

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

importScripts('resource.js');
Honora answered 22/10, 2018 at 7:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.