gigeos
gigeos

Reputation: 307

ios javascript pagehide and unload doesn't work correctly

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);

Upvotes: 3

Views: 5574

Answers (1)

Max Strater
Max Strater

Reputation: 538

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.

Upvotes: 1

Related Questions