从温和理解的地方更新:
我已经阅读了很多关于 Service Worker 的内容,并且推进了我正在从事的项目,远远超过了我写这篇文章时的水平。
我在这里探索的主要问题(firebase-messaging-sw.js
从域的根目录获得服务)已通过ServiceWorkerView
以下方式解决。
有趣的事实:事实证明,firebase-messaging-sw.js
从域的根目录提供服务的原因是 Service Worker 的控制范围是由 URL 定义的。所以,虽然:
http://whatever.com/firebase-messaging-sw.js
掌控一切,
http://whatever.com/static/firebase-messaging-sw.js
只能控制下面的所有内容/static/
(在这种情况下,只有 Django 提供的静态资源)。即使 JS 文件是静态的,它也需要控制该路径之外的页面。
原始问题:
如何让 FCM 服务人员 ( firebase-messaging-sw.js
) 在 Django 中工作?
我正在django
使用fcm-django
.
我如何firebase-messaging-sw.js
从根本上服务?
Django 默认在路径“/static/”下提供静态资源。将 STATIC_URL 更改为“/”可以firebase-messaging-sw.js
使用,但没有其他内容。
我尝试了将以下内容放入我的 urls.py 的建议:
url(r'^(?!/static/.*)(?P<path>.*\..*)$', RedirectView.as_view(url='/static/%(path)s'))
虽然显然是对正则表达式魔法的光荣使用,但事实证明服务工作者不能支持重定向。(我想这也与有趣的事实有关)
我在 urlconf 中写了一个由显式 URL 指向的视图。这样可行。
class ServiceWorkerView(View):
def get(self, request, *args, **kwargs):
return render(request, 'fcmtest/firebase-messaging-sw.js')
网址.py:
path('firebase-messaging-sw.js', views.ServiceWorkerView.as_view(), name='service_worker')
现在 urlhttp://localhost:8000/firebase-messaging-sw.js
提供了 javascript;但是,Firebase 抱怨内容类型是text/plain
所以我将视图更改为:
class ServiceWorkerView(View):
def get(self, request, *args, **kwargs):
return render(request, 'fcmtest/firebase-messaging-sw.js', content_type="application/x-javascript")
我得到的错误是:
Uncaught (in promise) TypeError: Failed to register a ServiceWorker: A bad HTTP response code (404) was received when fetch the script.
我的firebase-messaging-sw.js
(注意没有任何 console.log 语句打印):
importScripts("https://www.gstatic.com/firebasejs/5.2.0/firebase-app.js");
importScripts("https://www.gstatic.com/firebasejs/5.2.0/firebase-messaging.js");
importScripts("https://www.gstatic.com/firebasejs/5.2.0/init.js");
// Initialize Firebase
var config = {
apiKey: "AIzaSyBOb5gh1Lry84116M1uvAS_xnKtcWUoNlA",
authDomain: "pyfcm-5f794.firebaseapp.com",
databaseURL: "https://pyfcm-5f794.firebaseio.com",
projectId: "pyfcm-5f794",
storageBucket: "pyfcm-5f794.appspot.com",
messagingSenderId: "813943398064"
};
console.log('in service worker - before initializeApp')
firebase.initializeApp(config);
console.log('in service worker - after initializeApp')
const messaging = firebase.messaging();
console.log('in service worker - after firebase.messaging')
// if the app is in the background (user not on page)
messaging.setBackgroundMessageHandler(function(payload) {
console.log('in service worker - in setBackgroundMessageHandler')
const title = "Hello World";
const options = {
body: payload.data.status
}
return self.registration.showNotification(title, options);
});
最后,我的设备注册页面(我不确定如何运行 javascript 然后提交。form.submit() 不起作用,但这可能是因为其他事情不起作用..?(fcm/fcmtest/templates/fcmtest/device_registration.html
):
<head>
{% load static %}
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>FCM Device Registration</title>
<!-- update the version number as needed -->
<script src="https://www.gstatic.com/firebasejs/5.2.0/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "AIzaSyBOb5gh1Lry84116M1uvAS_xnKtcWUoNlA",
authDomain: "pyfcm-5f794.firebaseapp.com",
databaseURL: "https://pyfcm-5f794.firebaseio.com",
projectId: "pyfcm-5f794",
storageBucket: "pyfcm-5f794.appspot.com",
messagingSenderId: "813943398064"
};
firebase.initializeApp(config);
</script>
<script defer src="https://www.gstatic.com/firebasejs/5.2.0/firebase-app.js"></script>
<!-- include only the Firebase features as you need -->
<script defer src="https://www.gstatic.com/firebasejs/5.2.0/firebase-auth.js"></script>
<!--<script defer src="https://www.gstatic.com/firebasejs/5.2.0/firebase-database.js"></script>-->
<script defer src="https://www.gstatic.com/firebasejs/5.2.0/firebase-messaging.js"></script>
<!--<script defer src="https://www.gstatic.com/firebasejs/5.2.0/firebase-storage.js"></script>-->
<!-- initialize the SDK after all desired features are loaded -->
<!--<script defer src="https://www.gstatic.com/firebasejs/5.2.0/init.js"></script>-->
</head>
<body>
<script>
function deviceRegistration() {
console.log('in deviceRegistration()')
firebase.initializeApp(config);
const messaging = firebase.messaging();
// public key generated in firebase console
messaging.usePublicVapidKey("BMEoHrnzLq5WNeyahbSxJNTyS-44bXug2wetxAWVMLMSUIQE0dexhP4pJhcSA-ZlQlneHURmYQcnq9ofym_sStY");
// console.log('{% static "firebase-messaging-sw.js" %}')
console.log("/firebase-messaging-sw.js")
// changed location passed to navigator.serviceWorker.register since I am no longer serving firebase-messaging.js from localhost/static/ (see that url hack)
// navigator.serviceWorker.register('{% static "firebase-messaging-sw.js" %}')
navigator.serviceWorker.register("/firebase-messaging-sw.js")
.then((registration) => {
console.log('before messaging.useServiceWorker')
messaging.useServiceWorker(registration);
console.log('after messaging.useServiceWorker')
// Request permission and get token.....
messaging.requestPermission()
.then(function(){
console.log("Have Permission");
})
.then(function(token) {
form = document.getElementById("registration_form");
registration_token = messaging.getToken();
form.registration_id = registration_token;
var isAndroid = navigator.userAgent.toLowerCase().indexOf("android") >= -1;
if (isAndroid) {
form.type = "android";
} else {
var isiOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
if (isiOS) {
form.type = "ios";
} else {
form.type = "web";
}
}
//form.submit();
})
.catch(function(err){
console.log("Permission denied");
})
});
// request permission to send notifications
messaging.requestPermission()
.then(function(){
console.log("Have Permission");
})
.then(function(token) {
form = document.getElementById("registration_form");
registration_token = messaging.getToken();
form.registration_id = registration_token;
var isAndroid = navigator.userAgent.toLowerCase().indexOf("android") >= -1;
if (isAndroid) {
form.type = "android";
} else {
var isiOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
if (isiOS) {
form.type = "ios";
} else {
form.type = "web";
}
}
//form.submit();
})
.catch(function(err){
console.log("Permission denied");
})
// if user is on the page then show message directly instead of a notification
messaging.onMessage(function(payload) {
console.log('payload: ', payload);
});
}
</script>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form id="registration_form" method="post">{% csrf_token %}
<input id="name" type="text" />
<input id="type" type="hidden" />
<input id="user" type="hidden" value="{{ user.id }}" />
<input id="registration_id" type="hidden" />
<input id="btn_register" type="button" value="Register" onclick="deviceRegistration();" />
</form>
</body>
我尝试manifest.json
按照
https://firebase.google.com/docs/cloud-messaging/js/client上的说明添加一个
它目前由我的静态文件提供,并在注册和发送页面中链接
我的控制台中的错误:
Uncaught (in promise) TypeError: Failed to register a ServiceWorker: A bad HTTP response code (404) was received when fetch the script.
获取脚本时收到错误的 HTTP 响应代码 (404)。
加载资源失败:net::ERR_INVALID_RESPONSE
firebase-messaging-sw.js:3 未捕获
(匿名)@ firebase-messaging-sw.js:3
index.esm.js:1945 未捕获(承诺)
目的
浏览器错误消息:
“注册 ServiceWorker 失败:ServiceWorker 脚本评估失败”
代码:
“消息/失败的服务工作者注册”
信息:
“消息:我们无法注册默认服务工作者。无法注册服务工作者:服务工作者脚本评估失败(消息/失败的服务工作者注册)。”
堆:
“FirebaseError:消息:我们无法注册默认服务工作者。未能注册服务工作者:服务工作者脚本评估失败(消息/失败-服务工作者-注册)。↵在https://www.gstatic.com/firebasejs/5.2 .0/firebase-messaging.js:1:34104 "