We’re using WebPush in our newly migrated extension to MV3. It’s both for user-facing notifications and background updates. Some users have been complaining that they are seeing “Site has updated in the background” notifications even though our registration code is as follows:
chrome.runtime.onStartup.addListener(() => {
installWebPush();
});
chrome.runtime.onInstalled.addListener(() => {
installWebPush();
});
export async function installWebPush() {
const pushData = await registration.pushManager.subscribe({
userVisibleOnly: false,
applicationServerKey: urlB64ToUint8Array(PUBLIC_KEY),
});
if (pushData) {
await syncWebPushToken(JSON.stringify(pushData));
}
}
export async function syncWebPushToken(pushData) {
const { storedToken } = chrome.storage.local.get(["storedToken"]);
if (storedToken == pushData) {
return;
}
await fetch("https://example.com/web-push-tokens", {
method: "POST",
body: JSON.stringify({ token: pushData }),
});
chrome.storage.local.set({ storedToken: pushData });
}
function urlB64ToUint8Array(base64String) {
// From this page: https://developer.chrome.com/docs/extensions/how-to/integrate/web-push
}
Some users report seeing it all the time. I have been able to reproduce the issue by doing the following:
- Install our extension on one Chrome profile and make sure settings are synced
- Restart Chrome, but don’t open the profile with our extension, instead open another profile
- Wait for a silent push to arrive – then the “Site has updated in the background” notification appears
If I open the profile with the extension installed, then the notifications stop.
I was able to fix this by calling the subscription method in the main script of the service worker. Basically:
try {
registration.pushManager.subscribe({
userVisibleOnly: false,
applicationServerKey: urlB64ToUint8Array(PUBLIC_KEY),
}).catch(() => {
// This will fail
});
} catch (e) {
// Nothing to do here, this seems to update the registration in Chrome so it's marked `userVisibleOnly: false`
}
chrome.runtime.onStartup.addListener(() => {
installWebPush();
});
chrome.runtime.onInstalled.addListener(() => {
installWebPush();
});
I’m not sure if this is a bug or if there is something wrong with in what order we call all the registration code. But I created a reproduction repo here: https://github.com/feederco/mv3-user-facing-bug