Prevent WebPush init from attaching events multiple times

This commit is contained in:
Karina Kwiatek 2023-01-05 10:49:33 +01:00
parent eac82db8f4
commit e93531a4af
1 changed files with 19 additions and 15 deletions

View File

@ -3,25 +3,25 @@ import { enableHandler } from './enable';
import { dismissHandler } from "./dismiss"; import { dismissHandler } from "./dismiss";
import { unsubscribeHandler, checkSubscription } from "retrospring/features/webpush/unsubscribe"; import { unsubscribeHandler, checkSubscription } from "retrospring/features/webpush/unsubscribe";
let subscriptionChecked = false; let initialized = false;
export default (): void => { export default (): void => {
const swCapable = 'serviceWorker' in navigator; const swCapable = 'serviceWorker' in navigator;
const notificationCapable = 'Notification' in window; const notificationCapable = 'Notification' in window;
// We want to adjust enable/disable buttons on every page load
// because the enable button appears on both the settings and inbox pages.
if (swCapable && notificationCapable) { if (swCapable && notificationCapable) {
const enableBtn = document.querySelector('button[data-action="push-enable"]'); const enableBtn = document.querySelector('button[data-action="push-enable"]');
navigator.serviceWorker.getRegistration().then(async registration => { navigator.serviceWorker.getRegistration().then(async registration => {
const subscription = await registration?.pushManager.getSubscription(); const subscription = await registration?.pushManager.getSubscription();
if (subscription) { if (subscription) {
document.querySelector('button[data-action="push-enable"]')?.classList.add('d-none'); document.querySelector('button[data-action="push-enable"]')?.classList.add('d-none');
document.querySelector('[data-action="push-disable"]')?.classList.remove('d-none'); document.querySelector('[data-action="push-disable"]')?.classList.remove('d-none');
if (!subscriptionChecked) { if (!initialized) {
checkSubscription(subscription); checkSubscription(subscription);
subscriptionChecked = true;
} }
return; return;
} }
@ -34,6 +34,7 @@ export default (): void => {
}); });
} }
if (!initialized) {
registerEvents([ registerEvents([
{type: 'click', target: '[data-action="push-enable"]', handler: enableHandler, global: true}, {type: 'click', target: '[data-action="push-enable"]', handler: enableHandler, global: true},
{type: 'click', target: '[data-action="push-dismiss"]', handler: dismissHandler, global: true}, {type: 'click', target: '[data-action="push-dismiss"]', handler: dismissHandler, global: true},
@ -45,4 +46,7 @@ export default (): void => {
global: true global: true
}, },
]); ]);
initialized = true;
}
} }