如何在JavaScript中设置推送通知的显示时间?
问题描述:
这里是服务人员的侦听推送通知的代码:如何在JavaScript中设置推送通知的显示时间?
self.addEventListener('push', function (event) {
var payload = event.data ? event.data.text() : 'no payload';
event.waitUntil(
self.registration.showNotification('Notify Message', {
body: payload,
icon: 'push.png'
}) );
});
我有推送通知我的屏幕上时,来发送通知。但是我想在屏幕上显示推送通知一段时间(例如说90秒或发送通知的用户输入的动态持续时间)。这不适用于android或ios。这是桌面级通知。那么,如何设置推送通知的持续时间?
任何形式的帮助,高度赞赏。 感谢
答
没有看到你是如何显示您的通知,你可以实现一个简单的超时,沿着线的东西:
function clearNotice(notice) {
// notice.hide();
}
function showNotice(notice) {
notice.show();
// clear your notice
setTimeout(clearNotice(notice), notice.timeout);
}
答
没有听众用或属性来设置时间。您可以使用以下代码关闭通知:
Notification.requestPermission(function(result) {
if (result === 'granted') {
navigator.serviceWorker.ready.then(function(registration) {
registration.showNotification('Notify Message', {
body: payload,
icon: 'push.png'
}).then(function(event) {
console.log(event);
if(event && event.notification) {
setTimeout(function(){ event.notification.close();}, 3000);
}
});
});
}
});
答
您可以将requireInteraction参数设置为true,以使通知不会被自动解除。 当前没有持续时间的参数。 你可以在这里查看文档 https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration/showNotification
找到解决方案吗? –