I'm trying to create a Web Worker from my extension's content script, but it's getting blocked by a SecurityError (same origin policy). What's the best way to do this?
From my content script:
var workerURL = chrome.extension.getURL("js/searchWorker.js");
var lunrWorker = new Worker(workerURL);
From the manifest:
"content_scripts": [
{
"matches": ["http://localhost:8000/*"],
"js": ["js/jquery.min.js", "js/jquery.highlight.js", "js/index.js"],
"css": ["css/bootstrap.css", "css/styles.css"]
}
]
I also tried setting this in my manifest, but it didn't help:
"content_security_policy": "default-src 'none'; style-src 'self'; script-src 'self';",
(Sidenote: the CSS isn't being injected into the page, I'm not sure if that's a symptom of the same problem or unrelated)
http://crbug.com/357664 is the bug report about not being able to load extension scripts as a web worker.
The workaround to this problem is to load the worker script using XMLHttpRequest, then load the worker from a string. When I faced this problem in the past, I created a wrapper that transparently modifies the
Worker
constructor, so you can usenew Worker(chrome.runtime.getURL('worker.js'))
without any problems.See
patch-worker.js
(documentation) for the implementation of the previous idea.patch-worker.js
has some limitations (e.g.importScripts
does not work as expected), mainly related to the fact that it does not run in thechrome-extension:
-origin. To solve these problems, I created another library that uses an iframe to create the Worker. Seeworker_proxy
for the source code and documentation.