我使用Service Worker 向 chrome 浏览器发送推送通知。
我使用以下代码从服务器接收通知
var url = "path/to/your/json/file/json-data.php?param="+Math.random();
self.addEventListener('push', function(event) {
event.waitUntil(
fetch(url).then(function(response) {
if (response.status !== 200) {
// Either show a message to the user explaining the error
// or enter a generic message and handle the
// onnotificationclick event to direct the user to a web page
console.log('Looks like there was a problem. Status Code: ' + response.status);
throw new Error();
}
// Examine the text in the response
return response.json().then(function(data) {
if (data.error || !data.notification) {
console.log('The API returned an error.', data.error);
throw new Error();
}
var title = data.notification.title;
var message = data.notification.message;
var icon = data.notification.icon;
return self.registration.showNotification(title, {
body: message,
icon: icon,
data: {
url: data.notification.url
}
});
});
}).catch(function(err) {
console.log('Unable to retrieve data', err);
var title = 'An error occurred';
var message = 'We were unable to get the information for this push message';
var icon = 'img/design19.jpg';
var notificationTag = 'notification-error';
return self.registration.showNotification(title, {
body: message,
icon: icon,
tag: notificationTag
});
})
);
});
// The user has clicked on the notification ...
self.addEventListener('notificationclick', function(event) {
console.log(event.notification.data.url);
// Android doesn't close the notification when you click on it
// See: http://crbug.com/463146
event.notification.close();
// This looks to see if the current is already open and
// focuses if it is
event.waitUntil(
clients.matchAll({
type: "window"
})
.then(function(clientList) {
for (var i = 0; i < clientList.length; i++) {
var client = clientList[i];
if (client.url == '/' && 'focus' in client)
return client.focus();
}
if (clients.openWindow) {
return clients.openWindow(event.notification.data.url);
}
})
);
});
通知正在显示,但几秒钟后关闭。我不需要关闭通知。用户显式关闭通知。告诉我停止关闭通知的代码。一旦显示通知,它就不会永远关闭。用户显式关闭通知
return self.registration.showNotification(title, {
正文:消息,
图标:图标,
标签: 通知标签
});
您可以将 requireInteraction: true 添加到通知 porperties 字典中。这将使它留在屏幕上。请注意,这并不能保证在所有平台上都有效,但至少今天它在 chrome 桌面中工作正常。