9 javascript java android firebase firebase-cloud-messaging
我已经设置了一个网页(home.html),用户可以使用身份验证登录firebase.一旦进行身份验证,就会将其定向到新页面(test.html).一旦他们在这里,我希望能够发送通知或数据消息.
我想知道是否有人可以帮助我发送通知的代码 - 任何类型的通知.我已经在这3天了,不能从网上发送通知!我找不到任何关于此的教程 - 只有使用卷发的人.
我不知道如何处理下面的代码,这应该是关于如何向订阅主题的设备发送通知.我猜这是所有JSON,需要放入JSON对象?
请假设已填写初始化,我删除了所有信息 - 即使我认为该信息应该是公开的.
感谢您的任何信息!
这是我的服务工作者(到目前为止):firebase-messaging.sw.js
// Give the service worker access to Firebase Messaging.
// Note that you can only use Firebase Messaging here, other Firebase libraries
// are not available in the service worker.
importScripts('https://www.gstatic.com/firebasejs/4.3.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/4.3.1/firebase-messaging.js');
// Initialize Firebase
var config = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: ""
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function(payload){
const title = "Hello World";
const options = {
body: payload.data.status
};
return self.registration.showNotification(title, options);
});
Run Code Online (Sandbox Code Playgroud)
这是转到test.html页面的app.js文件
// Initialize Firebase
var config = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: ""
};
firebase.initializeApp(config);
// Retrieve Firebase Messaging object.
const messaging = firebase.messaging();
messaging.requestPermission()
.then(function() {
console.log('Notification permission granted.');
return messaging.getToken();
})
.then(function(token){
console.log(token);
})
.catch(function(err) {
console.log('Unable to get permission to notify.', err);
})
messaging.onMessage(function(payload){
console.log('onMessage:', payload);
});
Run Code Online (Sandbox Code Playgroud)
和准系统test.html文件
<!DOCTYPE html>
<html>
<head>
<script src="https://www.gstatic.com/firebasejs/4.3.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.3.1/firebase-messaging.js"></script>
</head>
<body>
<script src="/scripts/app.js"></script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
正如@Himanshu Chaudhary 所说。将通知从客户端推送到客户端并不是一个好的做法。人们在访问您的令牌时可能会误用通知。但这位蜜蜂说,如果你真的真的想这么做的话。可以说,为了测试 porpuse,私人项目...它只是从第二个客户端(或更好的服务器)到启用了通知的客户端的 http post:
var option = {
method: 'POST',
headers: new Headers({
Authorization: "key=AAAAnww...", // your Firebase cloud messaging Server key
"Content-Type": "application/json"
}),
body: JSON.stringify({
"notification": {
"title": "some tilte:",
"body": "more text",
"icon": "./src/assets/favicons/logo.png",
"click_action": deepLinkUrl
},
"to": token // the token from 'messaging.getToken(' from the reciving client
}),
mode: 'cors',
cache: 'default'
};
fetch('https://fcm.googleapis.com/fcm/send', option);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
714 次 |
| 最近记录: |