如何准确添加“Service-Worker-Allowed”以在上层文件夹中注册服务工作人员范围

新手上路,请多包涵

关于它也有类似的问题,但不太清楚如何应用该解决方案,并一直收到错误。

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

  • 索引.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 移动到上层文件夹中。但是有趣的是知道如何控制如何注册 service worker,尽管它在树文件夹应用程序中的位置……

其他建议…?

原文由 Falco 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.4k
2 个回答

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

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

现在在这篇文章 Understanding Service Worker scope 上针对类似的问题@Ashraf Sabry 回答说他可以使用 IIS Web 服务器的 web.config 文件更改标头。 –> 所以最后我明白要添加的标头是响应标头,但在浏览器解释响应之前 –> 如此处所述 https://learn.microsoft.com/en-us/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/plain'});
            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 文件。

现在应用程序可以正常工作,不会返回任何错误。作为对 fiddler 的最终证明跟踪请求,我可以清楚地看到对 app.js 的初始请求,响应中带有“Service-Worker-Allowed:/”;

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

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

原文由 Falco 发布,翻译遵循 CC BY-SA 4.0 许可协议

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

navigator.serviceWorker.register(href = '/service_worker.js', { scope: '/' })

我添加标头的方式是创建一个服务该 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

原文由 robert wallace 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题