我已遵循本教程:https://dzone.com/articles/how-to-add-real-web-push-notifications-to-your-web在我的Rails应用程序上启用推送通知。我正在使用webpush gem发送通知。
到目前为止,我所要做的就是让浏览器请求发送通知的权限,当我尝试调用send_web_push_notification方法(如下所示)时,第2行抛出了一个错误。
我认为这是因为我没有将用户的pushSubscription信息保存到数据库,但是我不知道该怎么做。在本教程中,最后一行是:“我们使用一个名为web_push_subscription的数据库JSON字段将pushSubscription信息保存在我们的用户上。”
有人可以向我展示如何执行此操作吗?
任何帮助将不胜感激。谢谢。
send_web_push_notification方法:
def send_web_push_notification(user_id)
subscription = User.find(user_id).web_push_subscription
message = {
title: "You have a message!",
body: "This is the message body",
tag: "new-message"
}
unless subscription.nil?
Webpush.payload_send(
message: JSON.generate(message),
endpoint: subscription["endpoint"],
p256dh: subscription["keys"]["p256dh"],
auth: subscription["keys"]["auth"],
ttl: 15,
vapid: {
subject: 'mailto:[email protected]',
public_key: Rails.application.config.webpush_keys[:public_key],
private_key: Rails.application.config.webpush_keys[:private_key]
}
)
end
end
serviceworker.js.erb:
function showNotification(event) {
return new Promise(resolve => {
const { body, title, tag } = JSON.parse(event.data.text());
self.registration
.getNotifications({ tag })
.then(existingNotifications => { // close? ignore? })
.then(() => {
const icon = `/path/to/icon`;
return self.registration
.showNotification(title, { body, tag, icon })
})
.then(resolve)
})
}
self.addEventListener("push", event => {
event.waitUntil(
showNotification(event)
);
}
});
self.addEventListener("notificationclick", event => {
event.waitUntil(clients.openWindow("/"));
});
application.js:
const permission = Notification.requestPermission();
if (permission !== 'granted') {
// no notifications
}else{
// yay notifications
}
function subscribeToPushNotifications(registration) {
return registration.pushManager
.subscribe({
userVisibleOnly: true,
applicationServerKey: window.vapidPublicKey
})
.then(pushSubscription => {
console.log(
"Received PushSubscription:",
JSON.stringify(pushSubscription)
);
return pushSubscription;
});
}
如果仔细查看代码,您会发现必须在数据库中创建Json字段以保存订阅。如果有可用订阅,则将发送推送通知。实际上,还有许多其他场景,如果您计划使用多个浏览器而不是要创建单独的表,则不必保存一个浏览器来进行用户通知,但是如果要添加一个浏览器来进行推送通知,则可以添加此表。用户表中的信息也是如此。创建新的迁移以更新您的用户表并添加以下列
t.json "web_push_subscription"
运行迁移,如果您清楚地注意到代码,则现在有了Json列,以下是用户数据库中所需的信息,当用户订阅推送通知时,将保存此信息
user. web_push_subscription[:endpoint] = what_ever_value_received
user.web_push_subscription[:auth] = what_ever_value_received
不幸的是,这只是个主意,因为我还没有实现它,但是我应该检查接收到的JSON.stringify(pushSubscription)对象,并且您收到的所有数据都有可能在此响应中,您可能需要按原样保存它您的订阅。您还需要保存权限,该用户确实允许您发送通知,如果是,则用户中的一个字段为boolean notification = true,因此您可以检查用户是否允许您发送通知,而不是可以发送,否则请发送。您还应该有办法在特定用户取消订阅通知时删除这些密钥。