javascript 如何准确添加“Service-Worker-Allowed”以在上层文件夹中注册 Service Worker 范围
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49084718/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How exactly add "Service-Worker-Allowed" to register service worker scope in upper folder
提问by Falco
There are similar questions about it, but it's not very clear how to apply the solution, and keep to receive an error.
关于它有类似的问题,但不是很清楚如何应用该解决方案,并保持收到错误。
I explain. I'd like to create a simply html/js app using service worker technology. I have:
我解释。我想使用服务工作者技术创建一个简单的 html/js 应用程序。我有:
- Index.html
- js/app.js
- js/sw.js
- 索引.html
- js/app.js
- js/sw.js
in app.js the code is (see //*** comments to clearify):
在 app.js 中的代码是(见 //*** 注释清除):
// *** I receive always the error:
// *** ERROR: The path of the provided scope ('/') is not under the max scope allowed ('/js/').
// *** Adjust the scope, move the Service Worker script, or use the Service-Worker-Allowed HTTP header to allow the scope.
var headers = new Headers();
// *** I set the header in order to solve the error above:
// *** The value is set to "/" because this js is included in html file in upper folder.
// *** I tried even "../" and many more others values...
headers.append('Service-Worker-Allowed', '/');
console.log(headers.get('Service-Worker-Allowed'));
if ('serviceWorker' in navigator) {
console.log('Start trying Registrating Scope');
// *** I register the service worker.
// *** The path of service worker is "js/sw.js" because this js is included in html file in upper folder.
// *** The path of scope is "../" because is the path used by service worker, and I want it uses upper folder scope.
navigator.serviceWorker.register('js/sw.js', {scope: '../'})
.then(function(reg) {
// registration worked
console.log('Registration succeeded. Scope is ' + reg.scope);
})
.catch(function(error) {
// registration failed
console.log('Registration failed with ' + error);
});
console.log('End trying Registrating Scope');
}
As you see in the comment I still get the error "The path of the provided scope ('/') is not under the max scope allowed ('/js/'). Adjust the scope, move the Service Worker script, or use the Service-Worker-Allowed HTTP header to allow the scope."
正如您在评论中看到的,我仍然收到错误“提供的范围 ('/') 的路径不在允许的最大范围 ('/js/') 下。调整范围,移动 Service Worker 脚本,或使用Service-Worker-Allowed HTTP 标头以允许范围。”
Maybe I could move the sw.js file, but I'd like to know what's wrong. Sure the problem is in how to register the header in the first 3 not commented lines of code.
也许我可以移动 sw.js 文件,但我想知道出了什么问题。当然问题在于如何在前 3 行未注释的代码行中注册标头。
Any advice of the code on how exactly register it?
关于如何准确注册代码的任何建议?
EDIT:
编辑:
What I'm missing is that what is to set is the request header, the header sent with the request, before asking the html page... I'm creating headers, useful eventually for a future new request. So js maybe is not the right place to put setting... The setting must be setted before the request to index.html is made, because what's setted in the html or js is setted for the response, or prepared for other requests
我缺少的是要设置的是请求标头,在询问 html 页面之前随请求发送的标头...我正在创建标头,最终对未来的新请求很有用。因此 js 可能不是放置设置的正确位置... 必须在对 index.html 发出请求之前设置该设置,因为 html 或 js 中设置的内容是为响应设置的,或者为其他请求准备的
now...
现在...
My approach now is to call another html page (register.html), in this page I'm tryng to $.ajax() the index.html page, with the right header setted: (I now it could be done with pure js, but for time saving I copy/pasted some already tested code)
我现在的方法是调用另一个 html 页面 (register.html),在这个页面中我尝试 $.ajax() index.html 页面,设置正确的标题:(我现在可以用纯 js 来完成,但为了节省时间,我复制/粘贴了一些已经测试过的代码)
$(document).ready(function(){
$.ajax({
type: "GET",
beforeSend: function(request) {
request.setRequestHeader("Service-Worker-Allowed", "/");
},
url: "index.html",
complete: function () {
window.location = "index.html";
}
});
});
I was hoping the first time hit on ajax call I could register the service worker, then redirecting on complete on index.html, I could find it already registered, but event this doesn't work...
我希望第一次打 ajax 调用时我可以注册服务工作者,然后在 index.html 上完成重定向,我可以发现它已经注册了,但事件这不起作用......
I repeat, quickest way is to move sw.js in upper folder. But it's interesting to know how to take control of how to register the service worker, despite of its position in tree folder application...
我再说一遍,最快的方法是将 sw.js 移动到上层文件夹中。但是知道如何控制如何注册服务工作者很有趣,尽管它在树文件夹应用程序中的位置......
other advices...?
其他建议...?
回答by Falco
Ok... I was a little confused, and even now I guess I have to get deep in the facts and study http headers better...
好吧...我有点困惑,即使现在我想我必须深入了解事实并更好地研究http标头...
Anyway as stated in many questions & answer on stackoverflow, it's not possible to alter headers during http request, unless it's not an ajax request (and that's not this case).
无论如何,正如在 stackoverflow 上的许多问题和答案中所述,在 http 请求期间不可能更改标头,除非它不是 ajax 请求(事实并非如此)。
now on this post Understanding Service Worker scopefor a similar question @Ashraf Sabry answered he could alter the headers using web.config file of IIS Web Server. --> So finally I understood that the header to add is a response header, but before the response is interpreted by the browser --> As stated here https://docs.microsoft.com/en-us/iis/configuration/system.webserver/httpprotocol/customheaders/that configuration is for response header.
现在在这篇文章中了解类似问题的服务工作者范围@Ashraf Sabry 回答说他可以使用 IIS Web 服务器的 web.config 文件更改标头。--> 所以最后我明白要添加的标头是响应标头,但在浏览器解释响应之前--> 如此处所述https://docs.microsoft.com/en-us/iis/configuration/ system.webserver/httpprotocol/customheaders/该配置用于响应头。
I guess there is not clear way to control that header to make service worker doing his work in a subfolder using html/javascript... It's a problem that could be solved only with server configurations.
我想没有明确的方法来控制该标头以让服务工作者使用 html/javascript 在子文件夹中完成他的工作......这是一个只能通过服务器配置来解决的问题。
A was doing my tests on Node, for didactical porpouse I tried to write a simple http server to test this issue starting from this tutorial https://ilovecoding.org/lessons/create-a-simple-http-server-with-nodejs
A 正在 Node 上做我的测试,对于教学海豚,我尝试编写一个简单的 http 服务器来测试这个问题,从本教程开始https://ilovecoding.org/lessons/create-a-simple-http-server-with-nodejs
the result is here (a "server.js" file runned on Node):
结果在这里(在 Node 上运行的“server.js”文件):
var http = require('http');
var url = require('url');
var querystring = require('querystring');
var fs = require('fs');
http.createServer(function(request, response){
pathName = url.parse(request.url).pathname;
console.log(pathName);
fs.readFile(__dirname + pathName, function(err, data){
if(err){
response.writeHead(404, {'Content-type':'text/plan'});
response.write('Page Was Not Found');
response.end();
}
else{
if(pathName.endsWith(".html")){
//response.writeHead(200, {'Service-Worker-Allowed':'/', 'Content-Type':'text/html'});
response.writeHead(200, {'Content-Type':'text/html'});
console.log("serving html");
}
else if(pathName.endsWith(".js")){
response.writeHead(200, {'Service-Worker-Allowed':'/', 'Content-Type':'application/javascript'});
//response.writeHead(200, {'Content-Type':'text/javascript'});
console.log("serving js");
}
else if(pathName.endsWith(".css")){
//response.writeHead(200, {'Service-Worker-Allowed':'/', 'Content-Type':'text/css'});
response.writeHead(200, {'Content-Type':'text/css'});
console.log("serving css");
}
else{
response.writeHead(200);
console.log("serving other");
}
response.write(data);
response.end();
}
})
}).listen(8080);
Using this js Node Server I could reach the same result stated for settings in IIS in the above link.
使用这个 js 节点服务器,我可以达到与上面链接中 IIS 中的设置相同的结果。
Note that after some test with this js, I reached that the file which needs "Service-Worker-Allowed:/" is the app.js file.
请注意,在使用此 js 进行一些测试后,我发现需要“Service-Worker-Allowed:/”的文件是 app.js 文件。
Now the application work as wanted returning no error. As final prove tracing requests on fiddler I can clearly see the initial request for app.js, with "Service-Worker-Allowed: /" in the response;
现在应用程序按需要工作,没有返回错误。作为对 fiddler 的最终证明跟踪请求,我可以清楚地看到 app.js 的初始请求,响应中带有“Service-Worker-Allowed: /”;
My conclusion is that not always it is possible to handle server configuration, so putting service worker file on root folder of the app is the best approach.
我的结论是,并非总是可以处理服务器配置,因此将 Service Worker 文件放在应用程序的根文件夹中是最好的方法。
Hope this could be helpful for some others...
希望这对其他人有帮助......
回答by AnthumChris
Service Workers cannot control pages that do not fall within their scope. Service worker /js/sw.jscannot control page /index.html, because that html file does not exist in the /js/folder (or subfolders of /js/). If you'd like /index.htmlto be controlled by a service worker, move the service worker to /sw.js.
Service Worker 无法控制不在其范围内的页面。Service Worker/js/sw.js无法控制 page /index.html,因为该文件/js/夹(或 的子文件夹/js/)中不存在该 html 文件。如果您想/index.html由 Service Worker 控制,请将 Service Worker 移至/sw.js。
It's easier to keep your code simple and put SWs in the proper folders (root if you manage the entire domain). This simplification avoids the unnecessary need to modify HTTP headers.
保持代码简单并将软件放在适当的文件夹中(如果您管理整个域,则为根)更容易。这种简化避免了不必要的修改 HTTP 标头的需要。

