问题
I'm getting the following error
Uncaught TypeError: Failed to execute 'postMessage' on 'DedicatedWorkerGlobalScope': The provided value cannot be converted to a sequence.
on this line in a webworker:
postMessage("hi", "http://localhost:8000");
(in fact, that is the entirety of the webworker).
The base file contains:
var myWorker = new Worker("test.js");
myWorker.onmessage = function (e) {
console.log('Message received from worker');
};
I'm not sure which value it's complaining about and I'm not sure what it means for it to be converted to a "sequence".
回答1:
The destination for the posted message is implicit (either the worker object the function is being called on, or the script that created the worker, when called from within the worker. So you should just use:
postMessage("hi");
See: postMessage on MDN
In case it's useful to others like myself who run into this problem for unrelated reasons, I was doing:
postMessage("type", value)
When I meant to do:
postMessage(["type", value])
回答2:
When I was trying to pass more than 1 parameter in postMessage
, same error message was displayed.
One solution is to pass it using JSON object.
For example: postMessage({'key1': 'value1','key2': 'value2'});
Then, when you want to access it, you can do the following:
onmessage = function(event){
var v1 = event.data.key1 ;
var v2 = event.data.key2;
}
来源:https://stackoverflow.com/questions/47299899/failed-to-execute-postmessage-on-dedicatedworkerglobalscope-the-provided-va