Question

I am working on a project that uses a web worker.

In my head section I have this code:

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

This works fine in Safari, but Chrome reports the following error:

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

Why does this work perfectly in Safari but not Chrome? How do I fix this?

Thank you.

Était-ce utile?

La solution

Chrome doesn't let you load web workers when running scripts from a local file.

Autres conseils

I use a workaround. Chrome blocks Worker but not <script>. Hence the best way to make a universal solution is this:

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();

You then link it as normal <script src="...". And once the function is defined, you use this abomination of a code:

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

The problem has been properly explained by Noble Chicken but I have a more general solution for it. Instead of installing wamp or xamp, with python you can navigate to the folder your project is hosted in and type: python -m http.server

Just that and you will have a running server on that folder, reachable from localhost.

You can also use the --allow-file-access-from-files flag when you launch Chrome.

Example for MacOsX :

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

More info : Web worker settings for chrome

It is because of the security restrictions. You need to use http:// or https:// protocol instead of file:///.

If you have NodeJS installed, you can simply do the following. - Note that this is one of many options available

Install local-web-server

$ npm install -g local-web-server

Now you can use it in any folder that you want to access the contents through http .

$ ws

Navigate to http://localhost:8000 (default port: 8000)

I had the same problem as your post too. The solution is that you have to run it with localhost (wamp or xamp). It will done.

Another workaround is use Google's web server for Chrome extension. Choose your work directory and start the server, Done!

This is inspired by Thomas answer above. But with one caveat that I wanted to distribute only the HTML, so i manually converted the js to dataURL. and enabling the data URL check box in it.

const myWorker = new Worker("data:application/x-javascript;base64,b25tZXNzYW...");

you need a web server for request from HTTP protocol Instead of local file and work correctly :)

Easy way to make local http server in chrome is this app:

Web Server for Chrome

https://chrome.google.com/webstore/detail/web-server-for-chrome/ofhbbkphhbklhfoeikjpcbhemlocgigb/related

Description:

A Web Server for Chrome, serves web pages from a local folder over the network, using HTTP. Runs offline. Web Server for Chrome is an open source (MIT) HTTP server for Chrome.

It runs anywhere that you have Chrome installed, so you can take it anywhere. It even works on ARM chromebooks.

It now has the option to listen on the local network, so other computers can access your files. Additionally, it can try and get an internet address.

Many people use this to do basic web development on a chromebook. It is also handy for sharing files over a local network between computers, or even on the internet.

Once you install it, navigate to http://127.0.0.1:8887

And it is not unsecure as flag --allow-file-access-from-files

Chrome load the file but cannot run it. Use Firefox. It's working for me.

With Python 2.x being more widely deployed than Python 3.x, something like python -m SimpleHTTPServer 8000 is more generally applicable, and not just for Mac OS X. I found it necessary for use under Cygwin, for instance.

With that in place, this example worked like a champ.

function worker_fun(num){
    num ++
    // console.log(num)
    postMessage(num);
    setTimeout(worker_fun.bind(null,num), 500)
}

var w

function startWorker(){
    var blob = new Blob([
        "onmessage = function(e){\
            " + worker_fun.toString() + "\
            worker_fun(e.data.num);}"
    ]);
    var blobURL = window.URL.createObjectURL(blob);
    if (typeof(Worker) != 'undefined'){
        if (typeof(w) == 'undefined'){

            w = new Worker(blobURL);
            w.onmessage = function(event){
                document.getElementById('num').innerHTML = event.data;
            } 
            w.postMessage({
               num:parseInt(document.getElementById('num').innerHTML)})
        }
    }
}


function stopWorker() { 
    w.terminate();
    w = undefined;
}

As mentioned chrome does not support it. I like to define my workers in the same file. This is a working workaround which will increase a number found in innerHTML of the element the with id=num every 500ms.

A probably reason is chrome doesn't let you load web workers when running scripts from a local file. And I try run the code on my firefox, can not either.

To load web worker from file in a project set up with Webpack and TypeScript I used a script as Tomáš Zato suggested. However, I had to modify the worker file.

worker.ts

(() => {
    console.log("worker_function loaded");
    // @ts-ignore
    window.worker_function = () => {
        self.onmessage = ({ data: { question } }) => {
            // @ts-ignore
            self.postMessage({
                answer: 42,
            });
        };
    }
})();

index.ts

async function run() {
    console.log('run()');

    const worker = new Worker(
        // @ts-ignore
        URL.createObjectURL(new Blob(["("+worker_function.toString()+")()"], { type: 'text/javascript' }))
    );

    worker.postMessage({
        question: 'The Answer to the Ultimate Question of Life, The Universe, and Everything.',
    });
    worker.onmessage = ({ data: { answer } }) => {
        console.log(answer);
    };
}

run();

index.html

<html lang="en-us">
  <head>
    <meta charset="utf-8" />
    <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
    <title>Offscreen canvas with web worker sample project</title>
    <script async type="text/javascript" src="worker.js"></script>
    <script async type="text/javascript" src="app.js"></script>
  </head>
  <body>
    <h1>web worker sample project</h1>
  </body>
</html>

webpack.config.js (version 5)

const path = require("path");
const CopyPlugin = require("copy-webpack-plugin");

module.exports = {
  mode: "production",
  entry: {
    app: "./src/index.ts",
    worker: "/src/worker.ts"
  },
  output: {
    filename: "[name].js",
    path: path.resolve(__dirname, "build")
  },
  performance: {
    hints: false
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: "ts-loader",
        exclude: /node_modules/
      },
    ]
  },
  resolve: {
    extensions: [".js", ".ts"]
  },
  plugins: [
    new CopyPlugin({
      patterns: [
        { from: "src/index.html", to: "" }
      ]
    })
  ]
};

Yes, It will not work in chorome if your are loading local file. But it will work fine in firefox browser. And you have to add below code in HTML file.

<head>
    <meta charset="UTF-8" />
</head>
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top