0

I simply want to save current state of my PWA in IndexedDB before leaving the page (when the user navigates to a new page, reloads the same page, or closes the tab/browser). But to my surprise, there is no reliable way to do this that works in all major browsers.

I've tested to capture window.onunload, window.onbeforeunload, window.onpagehide, window.onblur and document.onvisibilitychange. I can cover almost all cases, but not page reload on iOS Safari.

There are plenty of posts about this problem on Stackoverflow. Is there still no solution?

window.addEventListener('unload', function () {
  save();
});

window.addEventListener('beforeunload', function () {
  save();
});

window.addEventListener(
  'pagehide',
  function () {
    save();
  },
  false,
);

window.addEventListener('blur', function () {
  save();
});

document.addEventListener('visibilitychange', function () {
  save();
});
Mario Petrovic
  • 7,500
  • 14
  • 42
  • 62
Björn Morén
  • 693
  • 5
  • 14
  • 1
    Maybe `document.pagehide`. `blur` should be working. [Is there any way to use window.onbeforeunload on Mobile Safari for iOS devices?](https://stackoverflow.com/questions/4127621/is-there-any-way-to-use-window-onbeforeunload-on-mobile-safari-for-ios-devices) – Ouroborus Dec 15 '20 at 09:51
  • 2
    Come to think of it, you should probably just be storing state every time a meaningful change happens rather than waiting until unload. – Ouroborus Dec 15 '20 at 09:57
  • @Ouroborus Thanks for the suggestions. When you press the page reload button on Safari for iOS (iPhone) there is no pagehide or blur event. If there was a way to detect the browser reload button, it would solve my problem. I have lots of data, and want to avoid saving it for every small change the user makes, because it will slow down the app. – Björn Morén Dec 15 '20 at 10:10
  • 1
    No, there's no way to detect such a thing directly, before it actually happens, it needs to be inferred as you're doing. I have doubts that it would slow the app down as the IndexedDB API is asynchronous. If you'd need to update the database rapidly (more than, say, a few times a second), I would suggest re-examining what parts of state you actually need to save in preparation for a page reload. – Ouroborus Dec 15 '20 at 20:26
  • `onbeforeunload` will be triggered on reload with Google Chrome. – Jinghui Niu May 02 '22 at 21:41

0 Answers0