gpt4 book ai didi

javascript - 识别 JS 脚本何时作为 Worker 运行

转载 作者:可可西里 更新时间:2023-11-01 14:56:01 26 4
gpt4 key购买 nike

我有一个脚本可以直接运行,也可以在浏览器中作为 Web Worker 运行。我只想在作为 worker 运行时运行此脚本的一部分;所以我的问题是,脚本如何将自己标识为以这种方式运行?

我在规范中看不到任何允许这种情况发生的内容;我是否遗漏了一些明显的东西?

最佳答案

在以下内容中:

<html>
<head>
<title>Worker</title>
</head>
<body>
</body>
<script >
var w = new Worker ('worker.js');
w.onmessage = function (e) {
document.body.innerHTML += '<br>' + 'WORKER : ' + e.data;
};
</script>
<script src='worker.js'></script>
</html>

worker.js 作为脚本和 worker 被调用。

worker.js 包含:

  var msg = 'postMessage is ' + postMessage.toString () + 
', self.constructor is ' + self.constructor;
try {
postMessage (msg);
} catch (e) {
document.body.innerHTML += '<br>SCRIPT : ' + msg;
}

在 worker 环境中,postMessage 成功,在脚本环境中失败,因为它未定义,或者在浏览器中,它需要第二个参数。

输出是:

Chrome :

SCRIPT : postMessage is function () { [native code] }, self.constructor is function DOMWindow() { [native code] } 
WORKER : postMessage is function postMessage() { [native code] }, self.constructor is function DedicatedWorkerContext() { [native code] }

火狐浏览器:

SCRIPT : postMessage is function postMessage() { [native code] }, self.constructor is [object Window]
WORKER : postMessage is function postMessage() { [native code] }, self.constructor is function DedicatedWorkerGlobalScope() { [native code] }

歌剧:

WORKER : postMessage is function postMessage() { [native code] }, self.constructor is function Object() { [native code] }
SCRIPT : postMessage is function postMessage() { [native code] }, self.constructor is function Object() { [native code] }

全部在 Ubuntu 下。

关于javascript - 识别 JS 脚本何时作为 Worker 运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8523121/

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