如何精确添加“允许服务工作者”以在上层文件夹中注册服务工作者范围

Fal*_*lco 5 html javascript http-headers service-worker

关于它也有类似的问题,但是还不清楚如何应用该解决方案,并不断出现错误。

我解释。我想使用Service Worker技术创建一个简单的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');
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

编辑:

我所缺少的是要设置的是请求标头,即与请求一起发送的标头,然后询问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";
            }
        });
    });
Run Code Online (Sandbox Code Playgroud)

我希望第一次碰到ajax调用时我可以注册服务工作者,然后在index.html上完成重定向,我可以发现它已经注册,但是这行不通...

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

其他建议...?

Fal*_*lco 8

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

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

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

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

A在Node上进行测试,为了讲解流浪汉,我尝试编写一个简单的http服务器来测试此问题,从本教程https://ilovecoding.org/lessons/create-a-simple-http-server-with-nodejs开始

结果在这里(在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);
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

希望这对其他人有帮助...


rob*_*ace 7

我能够向根范围注册工作人员的方式是

navigator.serviceWorker.register(href = '/service_worker.js', { scope: '/' })
Run Code Online (Sandbox Code Playgroud)

我添加标头的方式是创建一个为该 service_worker 文件提供服务的新端点:

@app.route('/service_worker.js')
def service_worker():
    from flask import make_response, send_from_directory
    response = make_response(send_from_directory('static',filename='service_worker.js'))
    response.headers['Content-Type'] = 'application/javascript'
    response.headers['Service-Worker-Allowed'] = '/'
    return response
Run Code Online (Sandbox Code Playgroud)