From 03698896b314574bcae3360875cad224a45f5bb2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20Glawaty?= Date: Tue, 3 Sep 2024 14:33:23 +0200 Subject: [PATCH] Fixed multiple windows communication between closed banners --- src/banner/closing/closed-banner-store.mjs | 20 +++++++++++++++----- src/banner/closing/closing-manager.mjs | 9 ++++++++- 2 files changed, 23 insertions(+), 6 deletions(-) diff --git a/src/banner/closing/closed-banner-store.mjs b/src/banner/closing/closed-banner-store.mjs index 6c8c956..026c3ec 100644 --- a/src/banner/closing/closed-banner-store.mjs +++ b/src/banner/closing/closed-banner-store.mjs @@ -4,7 +4,7 @@ export class ClosedBannerStore { #maxItems; #loadedItems = null; - constructor({ storage, key, maxItems }) { + constructor({ storage, key, maxItems, onExternalChange }) { switch (storage) { case 'localStorage': if (!('localStorage' in window)) { @@ -34,13 +34,23 @@ export class ClosedBannerStore { this.#key = key; this.#maxItems = maxItems; - /*if (this.#storage instanceof Storage) { + if (onExternalChange && this.#storage instanceof Storage) { window.addEventListener('storage', event => { - if (null === event.key || this.#key === event.key) { - this.#loadedItems = null !== event.newValue && '' !== event.newValue ? event.newValue.split(',') : []; + if (!(null === event.key || this.#key === event.key)) { + return; + } + + const currentItems = this.#loadedItems || []; + const newItems = null !== event.newValue && '' !== event.newValue ? event.newValue.split(',') : []; + const diff = newItems.filter(id => !currentItems.includes(id)); + + this.#loadedItems = newItems; + + if (0 < diff.length) { + onExternalChange(diff); } }); - }*/ + } } persist(bannerId, closed) { diff --git a/src/banner/closing/closing-manager.mjs b/src/banner/closing/closing-manager.mjs index 123444c..2a4d201 100644 --- a/src/banner/closing/closing-manager.mjs +++ b/src/banner/closing/closing-manager.mjs @@ -23,7 +23,14 @@ export class ClosingManager { this.#frameMessenger = frameMessenger; const { storage, key, maxItems } = config; - this.#store = new ClosedBannerStore({ storage, key, maxItems }); + this.#store = new ClosedBannerStore({ + storage, + key, + maxItems, + onExternalChange: ids => { + ids.forEach(id => this.closeBanner(id)); + }, + }); if (this.#frameMessenger) { this.#frameMessenger.on('bannerClosed', ({ data }) => {