Chrome无法加载网络工作者

 北京雅舍 发布于 2023-01-30 19:07

我正在开发一个使用Web worker的项目.

在我的脑子部分,我有这个代码:

var worker = new Worker("worker.js");
// More code

这在Safari中运行良好,但Chrome报告以下错误:

Uncaught SecurityError: Failed to create a worker: script at '(path)/worker.js' cannot be accessed from origin 'null'.

为什么这在Safari中完美运行而不是Chrome?我该如何解决?

谢谢.

6 个回答
  • 从本地文件运行脚本时,Chrome不允许您加载Web工作程序.

    2023-01-30 19:09 回答
  • 我使用了一种解决方法.Chrome阻止Worker但不阻止<script>.因此,制定通用解决方案的最佳方法是:

    function worker_function() {
        // all code here
    }
    // This is in case of normal worker start
    // "window" is not defined in web worker
    // so if you load this file directly using `new Worker`
    // the worker code will still execute properly
    if(window!=self)
      worker_function();
    

    然后你正常链接它<script src="...".一旦定义了函数,就可以使用这种代码的憎恶:

    new Worker(URL.createObjectURL(new Blob(["("+worker_function.toString()+")()"], {type: 'text/javascript'})));
    

    2023-01-30 19:09 回答
  • 这个问题已由Noble Chicken正确解释,但我有一个更通用的解决方案.使用python而不是安装wamp或xamp,您可以导航到项目所在的文件夹并键入:python -m http.server

    就是这样,你将在该文件夹上有一个正在运行的服务器,可以从localhost访问.

    2023-01-30 19:09 回答
  • 启动Chrome时,您还可以使用--allow-file-access-from-files标志.

    MacOsX示例:

    /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --allow-file-access-from-files
    

    更多信息:Chrome的Web worker设置

    2023-01-30 19:09 回答
  • 这是因为安全限制.您需要使用http://https://协议而不是file:///.

    如果安装了NodeJS,则只需执行以下操作即可. - 请注意,这是许多可用选项之一

    安装local-web-server

    $ npm install -g local-web-server
    

    现在,您可以在要访问内容的任何文件夹中使用它http.

    $ ws
    

    导航到http://localhost:8000(默认端口:8000)

    2023-01-30 19:10 回答
  • 我的帖子也有同样的问题.解决方案是您必须使用localhost(wamp或xamp)运行它.它会完成.

    2023-01-30 19:10 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有