gpt4 book ai didi

javascript - 使用 Sharedworker 发送消息

转载 作者:行者123 更新时间:2023-12-01 02:00:26 24 4
gpt4 key购买 nike

使用给定的 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),

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

使用sharedworker语法,声明:

让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发布消息字符串?

最佳答案

这是 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 中提取的类型定义的一部分。我将提交一个拉取请求以尽快更新它。

关于javascript - 使用 Sharedworker 发送消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50641645/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com