worker-dom icon indicating copy to clipboard operation
worker-dom copied to clipboard

passing parameters

Open hyusetiawan opened this issue 5 years ago • 4 comments
trafficstars

how do you pass parameters into the worker-dom? globalThis is available inside the worker for onMessage but from the main thread, we can't seem to send anything into it Looked into the demo/ + issues, can't find any example

hyusetiawan avatar Apr 17 '20 15:04 hyusetiawan

I haven't looked at the implementation, but you'd need to get a reference to the Worker object that the lib creates.

trusktr avatar May 14 '20 03:05 trusktr

AMP version of the worker lib has exposeFunction(name, ref) global which allows to expose a function to the main thread. Not sure why it is not part of the regular lib.

In order to send information the other way around (Worker->Main), I am hijacking onmessage handler and consuming messages if I detect my own protocol, otherwise let the worker-dom library handle it.

v3nom avatar Jul 28 '20 15:07 v3nom

exportFunction(name, ref) is available only in AMP flavor of worker.js, which you can call like this:

MainThread.upgradeElement(document.getElementById('upgrade'), 'amp/worker.js').then(function (wd) {
  wd.callFunction(name, ...args) 
})

Alternatively, you can pass messages to and from generic worker like this:

MainThread.upgradeElement(document.getElementById('upgrade'), 'worker.js').then(function (wd) {
  wd.workerContext_.messageToWorker(message)
  wd.workerContext_.worker.onmessage = function (message) { ... }
})

niutech avatar Nov 03 '20 13:11 niutech

how do you pass parameters into the worker-dom?

Sending arbitrary messages into the worker isn't an explicitly supported use-case (yet). Some of the suggestions here involve calling into private APIs. These have the potential to stop working in any future release so proceed with caution. Can you give more details about what you're trying to build?

Not sure why it is not part of the regular lib.

We try not to add features unless there is demand for it, since all features come with a code-size cost. Adding support to non-AMP builds should be a relatively easy and small change! Feel free to make a PR :)

samouri avatar Nov 03 '20 14:11 samouri