从Chrome扩展程序内容脚本创建Web Worker [英] Create a Web Worker from a Chrome Extension content script

查看:318
本文介绍了从Chrome扩展程序内容脚本创建Web Worker的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从我的扩展的内容脚本中创建一个Web Worker,但它被SecurityError(同源策略)阻止。

从我的内容脚本中:

  var workerURL = chrome.extension.getURL(js / searchWorker.js); 
var lunrWorker = new Worker(workerURL);

从清单:

 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 ]
}
]

我也尝试在我的清单中设置它,但它没有帮助:

 content_security_policy:default-src'none'; style-src'self'; script-src'self';,

(旁注:CSS没有被注入到我不确定这是同一问题的症状还是无关紧要)

http://crbug.com/357664 是关于无法将扩展脚本加载为web worker的bug报告。



解决此问题的方法是加载工作者脚本使用XMLHttpRequest,然后从字符串中加载工作人员 。当我在过去遇到这个问题时,我创建了一个可以透明地修改 Worker 构造函数的包装器,因此您可以使用 new Worker(chrome.runtime。 getURL('worker.js'))没有任何问题。



请参阅 patch-worker.js 文档
$ b

patch-worker.js 有一些限制(例如 importScripts 不能按预期工作),主要与它不在 chrome-extension: -origin中运行的事实有关。为了解决这些问题,我创建了另一个使用iframe创建Worker的库。请参阅 worker_proxy 为源代码和文档。


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 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.

这篇关于从Chrome扩展程序内容脚本创建Web Worker的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆