#python #python-3.x #django #django-templates #progressive-web-apps
Вопрос:
Спасибо, что уделили мне время.
у меня есть веб-приложение Django, и я пытаюсь установить для него PWA.
Я размещал файлы ( sw.js, manifest.json, install_sw.html
) по URL-адресам с помощью класса TemplateView:
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
и даже с учетом того, что сотрудник службы найден и его код запущен, я не думаю, что он будет установлен.
Маяк сказал мне об этом, и когда я покидаю страницу, сотрудника службы больше нет в списке, поэтому я не могу запустить ее в автономном режиме, потому что кэш удаляется.
файлы под:
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')
манифест.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>
Ответ №1:
Ваш проект должен быть подан через localhost:[8000]
или HTTPS.
Если вы обслуживаете его в локальной сети, 192.168.43.101
вам следует изменить его на localhost или установить SSL crt. на нем.
Работникам сферы обслуживания требуется Безопасный контекст.
(Страница MDN, Хромированная страница).
Значение
window.isSecureContext
указывает, являются ли[SecureContext]
объекты видимыми или скрытыми. (Этоtrue
указано вfile://
URL-адресе, и API ServiceWorker будет виден, но, конечно, он не будет работать.)