使用Sharedworker进行Postmessage

时间:2018-06-01 10:41:30

标签: javascript typescript web-worker shared-worker

给定tsconfig.json,

{

    "compilerOptions": {

      "lib": ["es2015", "dom"]
    },
    "files": [
      "./1_webworker/tstut.ts",
      "./1_webworker/worker.ts"

    ]
  }

folder structure

npm install --save @types/sharedworker

在下面的代码中(来自./1_webworker/tstut.ts),

let worker: Worker = new Worker('worker.js');

使用sharedworker语法,声明:

let worker: SharedWorker.SharedWorker = new SharedWorker('worker.js');

但下面是错误。

worker.postMessage('do some work'); // Property 'postMessage' does not exist on type 'SharedWorker'

worker.addEventListener('message', (e) => {

  console.log(e.data); // Property 'data' does not exist on type 'Event'
});

如何将消息字符串发布到sharedworker?

1 个答案:

答案 0 :(得分:2)

以下是TypeScript中SharedWorker的一个工作示例。

caller.ts

let worker = new SharedWorker('worker.js');
worker.port.start();

worker.port.onmessage = function (e) {
    console.log('Caller Received:', e.data);
}

worker.port.postMessage('Message');

worker.ts

interface SharedWorkerGlobalScope {
    onconnect: (event: MessageEvent) => void;
}

const _self: SharedWorkerGlobalScope = self as any;

_self.onconnect = function (e) {
    var port = e.ports[0];

    port.addEventListener('message', function (e) {
        console.log('Worker Received', e.data);
        port.postMessage('Result');
    });

    port.start(); // Required when using addEventListener. Otherwise called implicitly by onmessage setter.
}

SharedWorkerGlobalScope目前是你从npm提取的类型定义的一部分。我将提交拉取请求,以便及时更新。