【问题标题】:Django ServiceWorker not in scopeDjango ServiceWorker 不在范围内
【发布时间】:2021-06-16 10:01:32
【问题描述】:

感谢您的宝贵时间。

我有一个 Django Web 应用程序并正在尝试为其设置 PWA。

我一直在使用 TemplateView 类通过 url 设置文件 (sw.js, manifest.json, install_sw.html):

urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    path('config/', include('config.urls')),
    path('products/', include('products.urls')),
    path('cart/', include('cart.urls')),
    path('accounts/', include('allauth.urls')),
    path('home/', home_view, name='home'),
    path('sw.js/', (TemplateView.as_view(template_name="admin/sw.js", content_type='application/javascript', )), name='sw.js'),
    path('manifest.json/', (TemplateView.as_view(template_name="admin/manifest.json", content_type='application/json', )), name='manifestjson'),
    path('install_sw/', (TemplateView.as_view(template_name="admin/install_sw.html", content_type='text/html', )), name='install_sw'),
]

urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

虽然我不断收到此错误:

no matching service worker detected. You may need to reload the page, or check that the scope of the service worker for the current page encloses the scope and start URL from the manifest

即使找到了 serviceworker 并且他的代码正在运行,我认为它没有被安装。

Lighthouse 告诉我,当我离开页面时,服务人员不在列表中,所以我无法脱机运行它,因为缓存被删除了。

文件位于:

sw.js:


{
    const cacheName = 'cache-v1';
    const resourcesToPrecache = [
        "{% url 'sw.js' %}",
        "{% url 'home' %}",
        "{% url 'install_sw' %}"
    ];

    self.addEventListener('install', function (event) {
        console.log('sw install event!');
        event.waitUntil(
            caches.open(cacheName)
                .then(function (cache) {
                    console.log('cache added')
                    return cache.addAll(resourcesToPrecache);
                }
                )
        );
    });

    self.addEventListener('fetch', function (event) {
        console.log(event.request.url);

        event.respondWith(
            caches.match(event.request).then(function (response) {
                return response || fetch(event.request);
            })
        );
    });
};

console.log('ok')

manifest.json

{
    "short_name": "Mega",
    "name": "MegaMagazine",
    "scope": "/",
    "icons": [
        {
            "src": "/static/m1.png",
            "type": "image/png",
            "sizes": "144x144"
        }
    ],
    "start_url": "/",
    "background_color": "#3367D6",
    "display": "standalone",
    "theme_color": "#3367D6",
    "prefer_related_applications": false
}

install_sw.html

<!doctype html>

<head>
    <link rel="manifest" href="{% url 'manifestjson' %}">
</head>
<title>installing service worker</title>

<body>
    <img src="/static/m1.png" alt="">
    <script type='text/javascript'>
        if ('serviceWorker' in navigator) {
            navigator.serviceWorker.register("{% url 'sw.js' %}").then(function (registration) {
                console.log('Service worker  registrado com sucesso:', registration, registration.scope);
            }).catch(function (error) {
                console.log('Falha ao Registrar o Service Worker:', error);
            });
        } else {
            console.log('Service workers não suportado!');
        }
    </script>

</body>

files

【问题讨论】:

    标签: python python-3.x django django-templates progressive-web-apps


    【解决方案1】:

    您的项目必须通过 localhost:[8000]HTTPS 提供服务。

    如果您在 192.168.43.101 等本地网络上提供它,则应将其更改为 localhost 或安装 SSL crt。 就可以了。

    服务人员requireSecure Context

    MDN pageChromium page)。

    window.isSecureContext的值表示是否 [SecureContext] 功能可见或隐藏。 (这是true file:// URL 和 serviceWorker API 将可见,但不会 工作,当然。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-19
      • 1970-01-01
      • 2021-06-01
      • 1970-01-01
      • 2022-01-05
      • 2015-02-26
      • 1970-01-01
      相关资源
      最近更新 更多