Skip to content
Snippets Groups Projects

Execute dynamic Script in Worker.

  • Clone with SSH
  • Clone with HTTPS
  • Embed
  • Share
    The snippet can be accessed without any authentication.
    Authored by Manfred Michaelis

    Executes a String containing some JavaScript code in a Worker. This script can contain callback functions and Promises.

    Edited
    exec-worker.js 552 B
    const func = '() => {const promise = sec => new Promise((resolve, reject) => setTimeout(() => resolve(["hello", sec]), sec * 1000)); promise(4).then(([msg, sec]) => self.postMessage(`${msg} after ${sec} seconds`))}';
    
    const dataObj = `self.postMessage((${func})());`; 
    const data = new Blob([dataObj], {type: 'application/javascript; charset=utf-8'});
    const uri = URL.createObjectURL(data);
    const worker = new Worker(`data:application/javascript,${encodeURIComponent(dataObj)}`);
    worker.onmessage = function(e) {
        console.log('Worker: ', e.data);
    };
    0% Loading or .
    You are about to add 0 people to the discussion. Proceed with caution.
    Finish editing this message first!
    Please register or to comment