Skip to content

Commit

Permalink
Integrate [data-turbo-temporary] with pagehide event
Browse files Browse the repository at this point in the history
Closes hotwired#1030

Add a [pagehide][] listener to the `CacheObserver` class to listen for
when the page has potential to enter the browser's [Back-Forward
Cache][bcfache].

When the event is dispatched with the [persisted][] set to `true`,
remove all temporary elements.

[pagehide]: https://developer.mozilla.org/en-US/docs/Web/API/Window/pagehide_event
[bfcache]: https://web.dev/articles/bfcache#observe_when_a_page_is_entering_bfcache
[persisted]: https://developer.mozilla.org/en-US/docs/Web/API/PageTransitionEvent/persisted
  • Loading branch information
seanpdoyle committed Nov 16, 2023
1 parent a247b35 commit 04221a9
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/observers/cache_observer.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,21 @@ export class CacheObserver {
if (!this.started) {
this.started = true
addEventListener("turbo:before-cache", this.removeTemporaryElements, false)
addEventListener("pagehide", this.removeTemporaryElementsPriorToEnteringBackForwardCache, false)
}
}

stop() {
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)
}
}

Expand Down
16 changes: 16 additions & 0 deletions src/tests/functional/cache_observer_tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,18 @@ test("removes temporary elements", async ({ page }) => {
assert.notOk(await hasSelector(page, "#temporary"))
})

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("removes temporary elements with deprecated turbo-cache=false selector", async ({ page }) => {
await page.goto("/src/tests/fixtures/cache_observer.html")

Expand All @@ -35,3 +47,7 @@ test("following a redirect renders [data-turbo-temporary] elements before the ca

assert.equal(await page.textContent("#temporary"), "data-turbo-temporary")
})

function haltTurboCaching(page) {
return page.evaluate(() => addEventListener("turbo:before-cache", (event) => event.stopImmediatePropagation(), { capture: true }))
}

0 comments on commit 04221a9

Please sign in to comment.