I want to send not only pushes with messages (via fetch) but sometimes also invisible push (i.e. do not show notification at all) just to check how much users still subscribed and how fast they receive a push.
I tried this code. It seems to work, but on some devices I get "This site has been updated in the background" message, which is confusing.
self.addEventListener('push', function(event) {
event.waitUntil(
fetch(my_awesome_url)
.then(function(response) {
if (response.status !== 200) {
throw new Error('Server code: ' + response.status);
}
return response.json().then(function(data) {
if (typeof data.data !== 'object') return; // invisible push, show nothing
var notificationData = {
body: data.content,
data: data.data,
tag: data.id || Math.random(),
icon: typeof data.data == 'object' ? data.data.image : ''
};
return self.registration.showNotification(data.title, notificationData);
});
})
.catch(function (err) {
})
);
});
How can I actually stop browser from showing anything?
You can't.
In your client side code you would have had to write the following line:
subscribe({userVisibleOnly: true});
This is because browsers only support push notifications where you show a message.
Don't try and send a message until you have to and then catch error responses for bad subscriptions.
There is a great answer to this question with more specifics here: Google Chrome Silent Push Notifications