如何精确添加“允许服务人员"?在上层文件夹中注册服务人员作用域 [英] How exactly add "Service-Worker-Allowed" to register service worker scope in upper folder

查看:100
本文介绍了如何精确添加“允许服务人员"?在上层文件夹中注册服务人员作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对此也有类似的问题,但不清楚如何应用该解决方案,并不断收到错误.

我解释.我想使用服务工作者技术创建一个简单的html/js应用程序. 我有:

  • Index.html
  • js/app.js
  • js/sw.js

在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');
}

正如您在评论中看到的那样,我仍然收到错误消息提供的范围('/')的路径不在允许的最大范围('/js/')之内.调整范围,移动Service Worker脚本,或使用Service-Worker-Allowed HTTP标头允许范围."

也许我可以移动sw.js文件,但是我想知道出了什么问题. 当然,问题在于如何在前3个未注释的代码行中注册标头.

有关如何准确注册代码的任何建议?

我所缺少的是要设置的是请求标头,即与请求一起发送的标头,然后询问html页面... 我正在创建标题,最终对于将来的新请求很有用. 所以js可能不是放置设置的正确位置... 必须在对index.html发出请求之前进行设置,因为html或js中的设置是为响应设置的,或者为其他请求准备的.

现在...

我现在的方法是调用另一个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";
            }
        });
    });

我希望第一次遇到Ajax调用,我可以注册服务工作者,然后在index.html上完成重定向,我可以发现它已经注册,但是如果这样做不起作用...

我重复一遍,最快的方法是将sw.js移动到上层文件夹中.但是,尽管它在树文件夹应用程序中的位置,但知道如何控制如何注册服务工作者还是很有趣的.

其他建议...?

解决方案

好...我有点困惑,即使现在我想我也必须深入了解事实并更好地研究http标头...

无论如何,无论是在许多问题中还是在&关于stackoverflow的答案,除非HTTP请求不是ajax请求,否则不可能在http请求期间更改标头(不是这种情况).

现在在此帖子中了解服务人员范围,以解决类似问题 @Ashraf Sabry回答说他可以使用IIS Web服务器的web.config文件更改标题. ->所以最后我理解要添加的标头是响应标头,但是在浏览器解释响应之前->如此处所述 https://docs.microsoft.com/zh-cn/iis/configuration/system.webserver/httpprotocol/customheaders/ 该配置用于响应头.

我想没有一个明确的方法来控制该标头,以使服务工作者使用html/javascript在子文件夹中完成工作……这是一个只有通过服务器配置才能解决的问题.

A在Node上进行测试,出于教学上的目的,我尝试编写一个简单的http服务器来从本教程开始测试此问题

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);

使用此js节点服务器,我可以达到上述链接中针对IIS中的设置所述的相同结果.

请注意,在对该js进行一些测试之后,我发现需要"Service-Worker-Allowed:/"的文件是app.js文件.

现在,应用程序可以按需工作,不返回任何错误. 作为对提琴手的最终证明跟踪请求,我可以清楚地看到对app.js的初始请求,响应中带有"Service-Worker-Allowed:/".

我的结论是,并非总是可以处理服务器配置,因此将服务工作者文件放在应用程序的根文件夹中是最好的方法.

希望这对其他人可能会有所帮助...

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:

  • Index.html
  • js/app.js
  • js/sw.js

in app.js the code is (see //*** comments to clearify):

// *** 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."

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.

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

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)

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

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

other advices...?

解决方案

Ok... I was a little confused, and even now I guess I have to get deep in the facts and study http headers better...

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

now on this post Understanding Service Worker scope for 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.

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.

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

the result is here (a "server.js" file runned on Node):

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.

Note that after some test with this js, I reached that the file which needs "Service-Worker-Allowed:/" is the app.js file.

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;

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.

Hope this could be helpful for some others...

这篇关于如何精确添加“允许服务人员"?在上层文件夹中注册服务人员作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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