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

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

  • WorkerGlobalScope
  • DedicatedWorkerGlobalScope
  • SharedWorkerGlobalScope