Skip to content
This repository was archived by the owner on Sep 11, 2024. It is now read-only.

Commit 34a6a9e

Browse files
committed
use pagehide instead of visibilitychange
1 parent e1008f9 commit 34a6a9e

File tree

2 files changed

+16
-7
lines changed

2 files changed

+16
-7
lines changed

src/utils/SessionLock.ts

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -208,13 +208,23 @@ export async function getSessionLock(onNewInstance: () => Promise<void>): Promis
208208
// Now add a listener for other claimants to the lock.
209209
window.addEventListener("storage", onStorageEvent);
210210

211-
// also add a listener to clear our claims when our tab closes (provided we haven't released it already)
212-
window.document.addEventListener("visibilitychange", (event) => {
213-
if (window.document.visibilityState === "hidden" && lockServicer !== null) {
214-
prefixedLogger.info("Unloading: clearing our claims");
211+
// also add a listener to clear our claims when our tab closes or navigates away
212+
window.addEventListener("pagehide", (event) => {
213+
// only remove the ping if we still think we're the owner. Otherwise we could be removing someone else's claim!
214+
if (lockServicer !== null) {
215+
prefixedLogger.info("page hide: clearing our claim");
215216
window.localStorage.removeItem(STORAGE_ITEM_PING);
216217
window.localStorage.removeItem(STORAGE_ITEM_OWNER);
217218
}
219+
220+
// It's worth noting that, according to the spec, the page might come back to life again after a pagehide.
221+
//
222+
// In practice that's unlikely because Element is unlikely to qualify for the bfcache, but if it does,
223+
// this is probably the best we can do: we certainly don't want to stop the user loading any new tabs because
224+
// Element happens to be in a bfcache somewhere.
225+
//
226+
// So, we just hope that we aren't in the middle of any crypto operations, and rely on `onStorageEvent` kicking
227+
// in soon enough after we resume to tell us if another tab woke up while we were asleep.
218228
});
219229

220230
return true;

test/utils/SessionLock-test.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -68,9 +68,8 @@ describe("SessionLock", () => {
6868
expect(await getSessionLock(onNewInstance1)).toBe(true);
6969
expect(onNewInstance1).not.toHaveBeenCalled();
7070

71-
// ... and is closed
72-
jest.spyOn(window.document, "visibilityState", "get").mockReturnValue("hidden");
73-
window.document.dispatchEvent(new Event("visibilitychange", {}));
71+
// ... and navigates away
72+
window.dispatchEvent(new Event("pagehide", {}));
7473

7574
// second instance starts as normal
7675
const onNewInstance2 = jest.fn();

0 commit comments

Comments
 (0)