mirror of
https://github.com/GoogleChrome/chrome-extensions-samples.git
synced 2026-03-27 13:29:34 +07:00
Service worker with push notification
This sample demonstrates using the Push API with self.registration.pushManager.subscribe() and specifically how to use userVisibleOnly to silence required notifications when receiving a push message in a service worker based extension.
Overview
By calling a method in the sample and using an external push server website we can simulate an extension receiving a push message where it is required to emit a notification and where it can bypass that requirement (userVisibleOnly = false).
Running this extension
- Clone this repository.
- Ensure your operating system allows your browser to show desktop notification. For MacOS this, for Google Chrome, requires "Google Chrome" and "Google Chrome Helper (Alerts)" to be allowed.
- Go to the web push test server and copy the “Public Key” to the
APPLICATION_SERVER_PUBLIC_KEYvariable in background.js. - Load this directory in Chrome as an unpacked extension.
- Click “service worker (Inactive)” on the extension to load DevTools for background.js
- In DevTools call:
await subscribeUserVisibleOnlyFalse(); - Copy the output after “Subscription data to be sent to the push notification server:” and paste it into the web push test server inside “Subscription to Send To” text box
- Enter some text into “Text to Send”
- Click “SEND PUSH MESSAGE”
- Observe that there is no notification with the text you sent in the browser and no generic notification notification being shown by the browser (that is usually enforced). You’ll see the text you sent in the DevTools log proving the extension service worker received the push data.