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

标签 javascript html web-worker

我有一个脚本可以直接运行,也可以在浏览器中作为 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/

相关文章:

flash - html5视频元素可以播放flash电影吗?

javascript - 如何处理对同一个 Web Worker 的多个请求

javascript - 如何在 Javascript 中执行非阻塞调用? ( promise 不会那样做。)

javascript - 如何使用数组缓冲区从 Web Workers 发送 JSON 数据

javascript - 检查悬停链接的 href 属性

javascript - 模式弹出后 Bootstrap 3 禁用背景

javascript - 客户端验证显示问题

html - 100% 高度 div

javascript - 如何在 Rhino 中运行 ES6 和 npm deps

javascript - 拒绝显示,将X-Frame-Options设置为SAMEORIGIN