到目前为止,我已经使用服务工作者,应用程序清单和Fire-base为我的角度应用程序创建了推送通知服务。
我正在获取服务器密钥和sender_id。我正在注册我的服务辅助角色并订阅push_messenger。
我也在使用谷歌本地服务器扩展来托管我的服务器。
主目录
Notification.requestPermission(function (status) {
console.log('Notification permission status:', status);
});
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('./service-worker.js', { scope: './' }).then(function (registration) {
// Registration was successful
console.log('ServiceWorker registration successful with scope: ', registration.scope);
console.log('registration: ', (registration));
navigator.serviceWorker.ready.then(reg => {
reg.pushManager.getSubscription().then(sub => {
if (sub == undefined) {
console.log('sub : ' + 'undefined');
navigator.serviceWorker.getRegistration().then((reg) => {
reg.pushManager.subscribe({
userVisibleOnly: true
}).then(sub => {
console.log('sub : ' + JSON.stringify(sub));
localStorage.setItem("sub", JSON.stringify(sub));
}, err => {
console.log('registration error occured: ' + err);
})
}, err => {
console.log('registration error occured: ' + err);
})
} else {
console.log('sub : ' + sub);
// subs = sub;
localStorage.setItem("sub", JSON.stringify(sub));
}
}, err => {
console.log('registration error occured: ' + err);
});
})
}).catch(function (err) {
// registration failed :(
console.log('ServiceWorker registration failed: ', err);
});
}
服务工作者.js
self.addEventListener('notificationclose', function(e) {
var notification = e.notification;
var primaryKey = notification.data.primaryKey;
console.log('Closed notification: ' + primaryKey);
});
self.addEventListener('notificationclick', function(e) {
var notification = e.notification;
var primaryKey = notification.data.primaryKey;
var action = e.action;
if (action === 'close') {
notification.close();
} else {
clients.openWindow('samples/page' + primaryKey + '.html');
notification.close();
}
// TODO - close all notifications when one is clicked
});
self.addEventListener('push', function(e) {
var body;
if (e.data) {
body = e.data.text();
} else {
body = 'Push message no payload';
}
var options = {
body: body,
icon: 'images/notification-flat.png',
vibrate: [100, 50, 100],
data: {
dateOfArrival: Date.now(),
primaryKey: 1
},
actions: [
{action: 'explore', title: 'Explore this new world',
icon: 'images/checkmark.png'},
{action: 'close', title: "I don't want any of this",
icon: 'images/xmark.png'},
]
};
e.waitUntil(
self.registration.showNotification('Push Notification', options)
);
});
节点服务器
var webPush = require('web-push');
var pushSubscription = {<subscription object>}
};
var payload = 'Sup Dude!';
var options = {
gcmAPIKey: *<server key>*,
TTL: 60,
};
webPush.sendNotification(
pushSubscription,
payload,
options
);
在上面的main.ts中,我能够在初始化应用程序时获取订阅对象。 并能够在那时发送推送通知。 但是当我从 chrome 打开相同的服务器 IP 时,我得到了不同的订阅对象。 有时我也使用 chrome 获得不同的订阅对象。
问题是我如何为所有用户发送推送通知,因为订阅对象不时不同,浏览器与浏览器不同。 (无法将所有数据存储到数据库中,这将占用过多的存储空间)
我认为你应该使用FCM来实现这个目的。您可以在其中创建组并向所有人发送通知。但即使要创建组,您也需要每个设备的 deviceId。
您可以将所有这些 id 存储在后端,并将 FCM 网页推送发送给所有人。
https://firebase.google.com/docs/cloud-messaging/js/client
您可以通过FCM文档来实现这一点。
这是官方的Firebase云消息文档非常有用...!
还可以在下面的链接下结帐,
Firebase Cloud-Messaging Google
Firebase 云消息凝视(订阅此频道)
这是我在客户端进行推送通知令牌注册的工作代码,可能适合您
<script>
messaging.requestPermission()
.then(function() {
console.log('Notification permission granted.');
// TODO(developer): Retrieve an Instance ID token for use with FCM.
messaging.getToken()
.then(function(currentToken) {
if (currentToken) {
console.log(currentToken);
settingTokenToServer(currentToken);
} else {
// Show permission request.
console.log('No Instance ID token available. Request permission to generate one.');
setTokenSentToServer(false);
refreshToken();
}
})
.catch(function(err) {
console.log('An error occurred while retrieving token............................... ', err);
});
})
.catch(function(err) {
console.log('Unable to get permission to notify.', err);
});
messaging.onTokenRefresh(function() {
messaging.getToken()
.then(function(refreshedToken) {
console.log('Token refreshed.');
// Indicate that the new Instance ID token has not yet been sent to the
// app server.
setTokenSentToServer(false);
// Send Instance ID token to app server.
sendTokenToServer(refreshedToken);
// ...
})
.catch(function(err) {
console.log('Unable to retrieve refreshed token ', err);
showToken('Unable to retrieve refreshed token ', err);
});
});
function settingTokenToServer(subscription_id) {
if (!isTokenSentToServer()) {
//setting token to FCM server
var ref = firebase.database().ref("notes/token");
ref.push({subscription_id}).then(function() {
console.log("Token saved Successfully..!");
}).catch(function(error) {
alert("Token not saved..." + error);
});
setTokenSentToServer(true);
} else {
console.log('Token already sent to server so won't send it again unless it changes');
}
}
function isTokenSentToServer() {
return window.localStorage.getItem('sentToServer') == 1;
}
function setTokenSentToServer(sent) {
window.localStorage.setItem('sentToServer', sent ? 1 : 0);
}
</script>