diff --git a/src/observers/cache_observer.js b/src/observers/cache_observer.js index 0eabf5680..7210e7949 100644 --- a/src/observers/cache_observer.js +++ b/src/observers/cache_observer.js @@ -8,6 +8,7 @@ export class CacheObserver { if (!this.started) { this.started = true addEventListener("turbo:before-cache", this.removeTemporaryElements, false) + addEventListener("pagehide", this.removeTemporaryElementsPriorToEnteringBackForwardCache, false) } } @@ -15,6 +16,13 @@ export class CacheObserver { if (this.started) { this.started = false removeEventListener("turbo:before-cache", this.removeTemporaryElements, false) + removeEventListener("pagehide", this.removeTemporaryElementsPriorToEnteringBackForwardCache, false) + } + } + + removeTemporaryElementsPriorToEnteringBackForwardCache = (event) => { + if (event.persisted) { + this.removeTemporaryElements(event) } } diff --git a/src/tests/functional/cache_observer_tests.js b/src/tests/functional/cache_observer_tests.js index 99441d6ae..c6e468f5d 100644 --- a/src/tests/functional/cache_observer_tests.js +++ b/src/tests/functional/cache_observer_tests.js @@ -15,6 +15,18 @@ test("test removes temporary elements", async ({ page }) => { assert.notOk(await hasSelector(page, "#temporary")) }) +test("test removes temporary elements when restoring from the browser's Back-Forward cache", async ({ page }) => { + await page.goto("/src/tests/fixtures/cache_observer.html") + await haltTurboCaching(page) + + assert.equal(await page.textContent("#temporary"), "data-turbo-temporary") + + await page.click("#link") + await page.goBack() + + assert.notOk(await hasSelector(page, "#temporary")) +}) + test("test removes temporary elements with deprecated turbo-cache=false selector", async ({ page }) => { await page.goto("/src/tests/fixtures/cache_observer.html") @@ -35,3 +47,7 @@ test("test following a redirect renders [data-turbo-temporary] elements before t assert.equal(await page.textContent("#temporary"), "data-turbo-temporary") }) + +function haltTurboCaching(page) { + return page.evaluate(() => addEventListener("turbo:before-cache", (event) => event.stopImmediatePropagation(), { capture: true })) +}