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.

Shahbaz Hashmi
  • 2,631
  • 2
  • 26
  • 49
Pedro Vanzella
  • 1,235
  • 1
  • 8
  • 13
  • 1
    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") – rajesh Jun 26 '16 at 06:46
  • 1
    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. – Karim H Nov 30 '16 at 17:19
  • 4
    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 environement – dectroo Mar 16 '17 at 22:59

2 Answers2

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

janniks
  • 2,942
  • 4
  • 23
  • 36
0

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

importScripts('resource.js');
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103