4

If I understand JavaScript workers correctly they have to be from the same domain as the main page. It would be awesome if SO Snippets could support another edit area or tab(s) for worker scripts.

This would be especially good as offscreen canvas comes on (apparently soon) line since it would allow posting working examples of using offscreen canvas.

1 Answer 1

3

While this feature could be useful, you can actually create JavaScript workers from a string, it just has to be converted to a Blob or DataURI. It's not too hard to do this, and here is an example that uses the body of a function as the script source.

var workerCode = ('' + function() {
	onmessage = function(e) {
		postMessage(e.data.split('').reverse().join(''));
	};
}).replace(/^[^{]*{([\s\S]*)}[^}]*$/, '$1');
var worker = new Worker(URL.createObjectURL(new Blob([workerCode])));
worker.onmessage = function(e) {
	console.log('From Worker: ' + e.data);
}
worker.postMessage('wolfrevO kcatS');

1
  • thanks! I thought of that but I thought it wouldn't work since it basically completely gets around the same origin restriction (unless I'm mis-understanding the restriction). I guess I should have tried it 😅
    – user128511
    Commented Nov 4, 2016 at 5:03

You must log in to answer this question.