diff --git a/libs/blocks/merch/merch.js b/libs/blocks/merch/merch.js index 767823f18d..0a5bcb8592 100644 --- a/libs/blocks/merch/merch.js +++ b/libs/blocks/merch/merch.js @@ -489,7 +489,7 @@ export async function openModal(e, url, offerType, hash, extraOptions) { const prevHash = window.location.hash.replace('#', '') === hash ? '' : window.location.hash; window.location.hash = hash; window.addEventListener('milo:modal:closed', () => { - window.history.replaceState({}, document.title, `#${prevHash}`); + window.history.pushState({}, document.title, `#${prevHash}`); }, { once: true }); } if (isInternalModal(url)) { @@ -747,3 +747,19 @@ export default async function init(el) { log.warn('Failed to get context:', { el }); return null; } + +export async function handleHashChange() { + const modalDialog = document.querySelector('.dialog-modal'); + if (window.location.hash) { + const modalId = window.location.hash.replace('#', ''); + const cta = document.querySelector(`.con-button[data-modal-id="${modalId}"]`); + if (cta && !modalDialog) { + reopenModal(cta); + } + } else if (modalDialog) { + const { closeModal } = await import('../modal/modal.js'); + closeModal(modalDialog); + } +} + +window.addEventListener('hashchange', handleHashChange); diff --git a/test/blocks/merch/merch.test.js b/test/blocks/merch/merch.test.js index 0e2786d48c..1017776a5b 100644 --- a/test/blocks/merch/merch.test.js +++ b/test/blocks/merch/merch.test.js @@ -27,6 +27,7 @@ import merch, { reopenModal, setCtaHash, openModal, + handleHashChange, } from '../../../libs/blocks/merch/merch.js'; import { mockFetch, unmockFetch, readMockText } from './mocks/fetch.js'; @@ -471,6 +472,35 @@ describe('Merch Block', () => { }); }); + describe('function "handleHashChange"', () => { + afterEach(() => { + document.querySelector('.dialog-modal')?.remove(); + document.querySelector('.con-button')?.remove(); + }); + + it('reopen modal after hash change', () => { + const cta = document.createElement('a'); + cta.classList.add('con-button'); + cta.setAttribute('data-modal-id', 'try-phsp'); + const clickSpy = sinon.spy(cta, 'click'); + document.body.append(cta); + window.location.hash = 'try-phsp'; + + handleHashChange(); + expect(clickSpy.called).to.be.true; + window.location.hash = ''; + }); + + it('close modal after hash change', () => { + const div = document.createElement('div'); + div.classList.add('dialog-modal'); + div.setAttribute('id', 'try-phsp'); + document.body.append(div); + + handleHashChange(); + }); + }); + describe('function "buildCta"', () => { it('returns null if context params do not have osi', async () => { const el = document.createElement('a');