Create a Web Worker from a Chrome Extension content script

久未见 提交于 2019-12-03 05:59:27

问题


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)


回答1:


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 use new 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 the chrome-extension:-origin. To solve these problems, I created another library that uses an iframe to create the Worker. See worker_proxy for the source code and documentation.



来源:https://stackoverflow.com/questions/22717586/create-a-web-worker-from-a-chrome-extension-content-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!