问题描述
第一次尝试网络工作者 API,似乎无法得到后台工作者的响应.
Trying out the web worker API for the first time and can't seem to get a response from the background worker.
标记:
<script src="~/Scripts/script.js"></script>
<button onclick="TriggerWorker()">Trigger Worker</button>
script.js 文件内容:
Contents of script.js file:
function TriggerWorker() {
var myWorker = new Worker('worker.js');
myWorker.onmessage = function (e) {
console.log(e.data);
}
console.log(myWorker);
myWorker.postMessage("Text sent to worker");
}
worker.js 文件内容:
Contents of worker.js file:
onmessage = function (e) {
postMessage('OK');
}
我可以让 myWorker 对象写入控制台,但响应OK"永远不会让它回到控制台.检查 myWorker 对象时,可以看到 onmessage 属性设置为权限被拒绝".
I can get the myWorker object to write to the console, but the response "OK" never makes it back into the console. When inspecting the myWorker object, I can see that the onmessage property is set to "Permission denied".
推荐答案
包含 worker onmessage 声明的文件的路径是相对于 html 文件 - 而不是调用脚本文件.
The path of the file containing the worker onmessage declaration is relative to the html file - not the calling script file.
我通过进行以下编辑使其正常工作:
I got it working by making the following edit:
var myWorker = new Worker('../Scripts/worker.js');
这篇关于<权限被拒绝>尝试实例化 Web Worker 对象时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!