Skip to content

Commit 55e5fcb

Browse files
authored
Conditionally add unload event listener (enable bfcache) (#127)
1 parent 157ac95 commit 55e5fcb

File tree

2 files changed

+24
-11
lines changed

2 files changed

+24
-11
lines changed

src/dom.js

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -571,9 +571,18 @@ export function popup(
571571
}
572572

573573
if (closeOnUnload) {
574-
window.addEventListener("pagehide", () => win.close());
575-
window.addEventListener("unload", () => win.close());
576-
window.addEventListener("beforeunload", () => win.close());
574+
window.addEventListener("beforeunload", () => {
575+
win.close();
576+
});
577+
if ("onpagehide" in window) {
578+
window.addEventListener("pagehide", () => {
579+
win.close();
580+
});
581+
} else {
582+
window.addEventListener("unload", () => {
583+
win.close();
584+
});
585+
}
577586
}
578587

579588
return win;
@@ -1035,6 +1044,7 @@ export function watchElementForClose(
10351044
handler: () => mixed
10361045
): CancelableType {
10371046
handler = once(handler);
1047+
const terminationEvent = "onpagehide" in window ? "pagehide" : "unload";
10381048

10391049
let cancelled = false;
10401050
const mutationObservers = [];
@@ -1054,7 +1064,7 @@ export function watchElementForClose(
10541064
}
10551065
if (sacrificialFrameWin) {
10561066
// eslint-disable-next-line no-use-before-define
1057-
sacrificialFrameWin.removeEventListener("unload", elementClosed);
1067+
sacrificialFrameWin.removeEventListener(terminationEvent, elementClosed);
10581068
}
10591069
if (sacrificialFrame) {
10601070
destroyElement(sacrificialFrame);
@@ -1097,7 +1107,7 @@ export function watchElementForClose(
10971107
sacrificialFrame.style.display = "none";
10981108
awaitFrameWindow(sacrificialFrame).then((frameWin) => {
10991109
sacrificialFrameWin = assertSameDomain(frameWin);
1100-
sacrificialFrameWin.addEventListener("unload", elementClosed);
1110+
sacrificialFrameWin.addEventListener(terminationEvent, elementClosed);
11011111
});
11021112
element.appendChild(sacrificialFrame);
11031113

test/tests/dom/popup.js

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -23,12 +23,15 @@ describe("popup", () => {
2323
closeOnUnload: 1,
2424
});
2525

26-
if (!listeners.unload) {
27-
throw new Error(`Popup should have unload listener registered.`);
28-
}
29-
30-
if (!listeners.pagehide) {
31-
throw new Error(`Popup should have pagehide listener registered.`);
26+
// Check that either pagehide or unload is registered (but not both)
27+
if ("onpagehide" in window) {
28+
if (!listeners.pagehide) {
29+
throw new Error(`Popup should have pagehide listener registered.`);
30+
}
31+
} else {
32+
if (!listeners.unload) {
33+
throw new Error(`Popup should have unload listener registered.`);
34+
}
3235
}
3336

3437
if (!listeners.beforeunload) {

0 commit comments

Comments
 (0)