【问题标题】:Why does this Service Worker manifest changes request URL for icon images为什么此 Service Worker 清单更改图标图像的请求 URL
【发布时间】:2021-07-22 08:56:27
【问题描述】:

我有一个 JavaScript 文件,其中服务工作者逻辑内容请求 URL 嵌套在一个目录中。我有能力并且已经将 Web 服务器配置为使用 HTTP 标头 Service-Worker-Allowed 作为“/”来提供该文件。

清单文件也位于反映请求 URL 的目录中。但是,假设将相同的请求 URL 设置为主范围,则设置范围和图像。

我看到的实际请求 URL 是相对于清单中的目录设置的,而不是我想要开始的根目录。

所以这是浏览器的时间线:

首先,请求返回索引文件的网站:https://localhost:3000

index.html

<!DOCTYPE html>
<html lang="en-US">
    <head>
        <link rel="manifest" href="json/manifest.json" async>
        <script id="js-webapp" type="module" src="js/webapp.js" defer async></script>
    </head>
    <body>
    </body>
</html>

其次,它解析并请求主应用逻辑:https://localhost:3000/js/webapp.js

webapp.js

window.addEventListener('load', function (event) {
    const path = '/js/sw.js'
    
    if ('serviceWorker' in navigator) {
        console.log('Service Worker present')
        navigator.serviceWorker.register(path, { scope: './'})
            .then((registration) => {
                console.log('Service Worker Registered', registration)
            })
            .catch((err) => {
                console.log('Service Worker Failed to Register: ', err)
        })
    }
})

第三,我的应用逻辑根据浏览器配置决定是否加载一个Service Worker文件:https://localhost:3000/js/sw.js。 (这是具有响应 key-val "service-worker-allowed" 和 "/" 的 HTTP 标头。

sw.js

const cacheName = 'v1.0.0'
const cacheFiles = [
    './manifest.json',
    './css/theme.css',
    './js/webapp.js',
    './img/logo.ico'
]
self.addEventListener('install', (event) => {
    console.log('Installed')

event.waitUntil(
    caches.open(cacheName).then((cache) => {
        console.log('Caching cacheFiles')
        return cache.addAll(cacheFiles)
        })
    )
})

接下来,Service Worker 请求清单以缓存文件:https://localhost:3000/json/manifest.json。 (这是在主索引文件上加载的,但在没有触发服务工作者逻辑的情况下,不会对此文件执行任何操作。)

manifest.json

{
    "name": "Web App",
    "short_name": "",
    "start_url": "/",
    "scope": "/",
    "display": "standalone",
    "display": "fullscreen",
    "theme_color": "#404040",
    "background_color": "#404040",
    "icons": [
        {
            "src": "img/ic_launcher_48.png",
            "sizes": "48x48",
            "type": "image/png"
        },
        ...
    ]
}

按照这个逻辑,我希望 URL 请求是 https://localhost:3000/img/ic_launcher_48.png。但是,我看到浏览器执行的请求 URL 是https://localhost:3000/json/img/ic_launcher_48.png

如果我在提供安装、激活和获取服务工作者逻辑的主文件时已经在标头中设置了服务工作者允许 HTTP,我做错了什么?

从其他 JavaScript 加载的所有其他内容,或 HTML 文件正确加载。

【问题讨论】:

    标签: service-worker


    【解决方案1】:

    图标src 与清单文件所在的位置相关,因为您的清单位于/json,那么浏览器正在寻找位于/json/img 的图标

    【讨论】:

    • 有没有办法改变它并使其与主网站相关?
    • 将清单 json 文件移动到目录的根目录。理想情况下,它应该始终位于根目录
    猜你喜欢
    • 2016-09-14
    • 2018-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-02
    • 2014-01-02
    • 1970-01-01
    相关资源
    最近更新 更多