这可能属于“不要那样做”的类别,但我正在尝试开发一个 chrome 扩展,它可以有效地将 Web 可访问的服务 worker 脚本(“sw.js”)注入(inject)用户页面,然后注册该脚本的服务人员。
现在,我有以下内容:
list .json:
{
"manifest_version": 2,
"name": "MyApp",
"description": "none",
"version": "1.0",
"incognito": "split",
"web_accessible_resources": ["sw.js"],
"permissions": [
"webRequestBlocking","webRequest",
"*://*/*"
],
"background":
{
"scripts": ["background.js"]
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["initPage.js"],
"all_frames": false
}]
}
背景.js
chrome.webRequest.onBeforeRequest.addListener(
function(details) {
return {redirectUrl: chrome.extension.getURL("sw.js")};
},
{urls: ["*://*/switchme.js"]},
["blocking"]);
initPage.js:
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/switchme.js').then(function(registration) {
console.log('ServiceWorker registration successful with scope: ', registration.scope);
}).catch(function(err) {
console.log('ServiceWorker registration failed: ', err);
})
}
希望从这里,你会看到我想要完成的事情。基本上,我想尝试将服务人员注册到
sw.js
,它托管在扩展程序的 web-accessible-scripts 中。我相信我可以做到这一点的方法是拦截对 switchme.js
的请求。并将其重定向到返回 sw.js
.这种方法的唯一问题是,当我尝试这样做时,我的 chrome 浏览器崩溃了。我将堆栈跟踪到
extensions::sendRequest
的行:nativeFunction(functionName,
request.args,
requestId,
hasCallback,
optArgs.forIOThread,
optArgs.preserveNullInObjects);
任何调试想法或耳光,并很好地解释了为什么我疯狂地认为这可能有效,我们将不胜感激。
最佳答案
浏览器崩溃似乎与this reported bug on the chromium issue tracker有关.
但是,请注意 this change in the chromium source ,表明问题不再在于从扩展的 URL 注册服务 worker 。
从提交消息:
[Service Worker Registration] Registered extension scheme to allow service workers
Service Workers require a secure origin, such as HTTPS. chrome-extension:// pages are not HTTP/HTTPS, but are secure so this change becomes a necessary step to allow extensions to register a Service Worker.
"chrome-extension" is added as a scheme allowing service workers.
作为脚注,chrome 扩展中的服务 worker 仍在进行中。您可以通过跟踪 this issue 来跟踪其进度。 .
关于javascript - 如何将服务 worker 注册到重定向的脚本 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30743468/