是的,几乎可以将通知从网站推送到网络浏览器,
您可以利用客户端 java 脚本进行用户同意和注册,并利用服务器端进程基于某些业务事件向用户推送通知。
客户端 -
注册你的服务工作者(大多数现代浏览器都支持它-
Notification.requestPermission().then(function (status) {
if (status === 'denied') {
\\You can add logging here
}
else if (status === 'granted') {
initialiseServiceWorker();
}
}
function initialiseServiceWorker() {
navigator.serviceWorker.register('serviceWorker.js', { scope: './' })
.then(handleSWRegistration)
.catch(function (err) {
console.log('[initialiseServiceWorker] : req.register serviceWorker unable to get serviceWorker file.', err);
});
};
function handleSWRegistration(event) {
if (event.installing) {
console.log('[handleSWRegistration] : Service worker installing');
} else if (event.waiting) {
console.log('[handleSWRegistration] : Service worker installed');
} else if (event.active) {
console.log('[handleSWRegistration] : Service worker active');
}
}
服务器端-
您可以使用任何服务器端实现GitHub Nuget
下面是来自 C# 库实现之一的 sn-p-
var vapidDetails = new VapidDetails("mailto:abcw@abc.com", _vapidPublicKey, _vapidPrivateKey);
var pushSubscription = new PushSubscription(PushEndpoint, PushP256DH, PushAuth);
var payLoad = new
{
message = $"Hello from Notification.",
title = "Notification!"
};
string strPayload = JsonConvert.SerializeObject(payLoad);
webPushClient.SendNotification(pushSubscription, strPayload, options);
您可以参考此链接了解架构流程-
PushNotification