3

I would like display a popup when the user close tab or refresh page on ios to prevent him he will lose his datas. I have seen unload is deprecated and I have to use pagehide event but it seems the both don't work on safari and even chrome.

My code is:

window.addEventListener("pagehide", function (evt) {
    return confirm("Vous allez perdre toutes vos modifications");
}, false);

The problem is the page refresh even if I click on cancel button, and the popup doesn't appear if I close the tab.

i tried this code too for Chrome mobile (desktop work fine) but the both don't work with his browser

window.addEventListener("beforeunload", function (e) {
    if (closeWindow) {
        var message = 'Toutes vos modifications seront perdues';
        if (typeof evt == 'undefined') {
            evt = window.event;
        }
        if (evt) {
            evt.returnValue = message;
        }
        return message;
    }
}, false);
Howard Renollet
  • 4,609
  • 1
  • 24
  • 31
gigeos
  • 308
  • 5
  • 14
  • Did you positively try to interact with the page before testing? There are indications that some browser implementations require user interaction with the page (whatever that means) before honoring the prompt in pagehide/beforeunload. – G. Stoynev Sep 25 '19 at 03:29

1 Answers1

1

My guess is that unload fires too late to pop up a message. You can sometimes get around this by using beforeunload, but it is not implemented in iOS Safari. :( Perhaps you can do something tricky with sending off an AJAX request to the server on unload (see: How to detect unsaved data in form when user leaves the page?).

I'm not sure it'll help, but you could also think about automatically saving the user's data on unload by saving it to localstorage or sending it to your server.

Community
  • 1
  • 1
Max Strater
  • 540
  • 6
  • 17
  • 1
    Fun fact: as of checking today, [caniuse.com says](https://caniuse.com/#search=beforeunload) the `beforeunload` event is supported by all browsers. However, as you've mentioned, I've confirmed in my case that `beforeunload` does not work on iOS 12. – Caleb Faruki Oct 15 '18 at 23:59