如何使用Blob创建SharedWorker?

时间:2018-11-18 11:27:14

标签: javascript web-worker

我要按照一本好书的一章中所述创建一个SharedWorker:https://github.com/getify/You-Dont-Know-JS/blob/master/async%20%26%20performance/ch5.md

我能够为正常网络工作者制作一个很好的例子:

function createAsker(limit) {
    var blob = new Blob(["onmessage = function(e) { " +
                           "if (self.higher === undefined) self.higher = " + limit + "; " +
                           "if (self.lower === undefined) self.lower = 1;" +
                           "if (e.data === 'correct') { " +
                             "postMessage('Party time'); " +
                           "} else {" +
                             "if (e.data === 'greater') self.lower = parseInt((self.lower + self.higher) / 2);" +
                             "if (e.data === 'lower') self.higher = parseInt((self.lower + self.higher) / 2);" +
                             "postMessage(parseInt((self.lower + self.higher) / 2));" +
                           "}" +
                         "}"]);
    var blobURL = window.URL.createObjectURL(blob);
    var worker = new Worker(blobURL);
    return worker;
}

var asker = createAsker(1000);

function createAnswerer(limit) {
    var blob = new Blob(["onmessage = function(e) { " +
                            "postMessage((e.data == " + limit + ") ? 'correct' : ((e.data < " + limit + ") ? 'greater' : 'lower'));" +
                         "}"]);
    var blobURL = window.URL.createObjectURL(blob);
    var worker = new Worker(blobURL);
    return worker;
}

var answerer = createAnswerer(42);

asker.onmessage = function(e) {
  console.log('Asker says: ' + e.data);
  if (e.data !== "Party time") {
    setTimeout(function() {answerer.postMessage(e.data)}, 1000);
  }
};

answerer.onmessage = function(e) {
  console.log('Answerer says: ' + e.data);
  setTimeout(function() {asker.postMessage(e.data)}, 1000);
};

asker.postMessage('start');

但是,我在创建共享工作者方面有困难。我试图用以下代码创建一个:

function createWorker() {
    var blob = new Blob(['addEventListener( "connect", function(evt){ ' +
                            'var port = evt.ports[0]; ' +
                            'port.addEventListener( "message", function(evt){' +
                              'port.postMessage( .. );debugger;' +
                            '} );' +
                            'port.start();' +
                          '} );']);
    var blobURL = window.URL.createObjectURL(blob);
    var w = new SharedWorker(blobURL);
    return w;
}

var w = createWorker();

w.port.start();

w.port.onmessage = function(e) {
  console.log(e.data);
};

w.port.onmessage('foobar');

,并且在发送foobar消息后,我希望我的共享工作人员发布一条消息,或者至少我希望调试器将其引导到代码中,但是,当我运行此代码时,控制台会给出两个未定义的响应。

1 个答案:

答案 0 :(得分:1)

Base64编码提供了一个永久URL,直到源代码更改为止。

const source = 'importScript("https://anotherhost/worker.js")';
const url = 'data:application/javascript;base64,' + btoa(source);
const worker = new SharedWorker(url);

它至少在Chrome 73和Firefox 66中有效。

有一个limit to the length的编码URL大约为65 KB。