Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Failed to execute 'postMessage' on 'DedicatedWorkerGlobalScope': Value at index 0 does not have a transferable type

This is the code of my worker:

onmessage = function (event) {
    postMessage({'data': event.data}, ['http://localhost:9000']);
};

And this is the code where I use the worker:

var worker = new Worker("/path/to/my/worker.js");
worker.onmessage = function (event) {
    console.log("RECEIVED: ", event.data);
};
worker.onerror = function (err) {
    console.log('ERROR: ', err)
};
worker.postMessage({'data': 'blabla', 'msg': 'Hi'});

But when the postMessage in the worker code is called, it gives me this error: "Failed to execute 'postMessage' on 'DedicatedWorkerGlobalScope': Value at index 0 does not have a transferable type."

I've tried also to serialize the object with this code:

onmessage = function (event) {
        postMessage(JSON.stringify({'data': event.data}), ['http://localhost:9000']);
    };

But nothing has changed.

------ EDIT ----------------------------------------------------------------

I tried the following code in the worker file:

function count() {
    var i = 0;
    self.onmessage = function (event) {
        postMessage("Hello " + event.data);
    };

    for (i = 0; i < 5; i++) {
        postMessage(i);
    }
    postMessage("Finished");
}

count();

The postMessage inside the onmessage function is the only one which gives me an error.

like image 717
Chiara Avatar asked Nov 03 '16 16:11

Chiara


1 Answers

The second parameter of Worker.postMessage() is meant to hold a list of objects of which you want to transfer ownership to your main window. This is restricted to some specific types (mostly ArrayBuffers and Bitmaps).

Explaining the error message: Your second parameter is ["some string"] with "some string" at index 0 and JS believes you want to transfer that object (which obviously wasn't your intention).

Just remove ['http://localhost:9000'] and you should be fine.

See https://developer.mozilla.org/en-US/docs/Web/API/Worker/postMessage for details and examples.

like image 152
Kai Giebeler Avatar answered Oct 31 '22 17:10

Kai Giebeler