Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safari: onbeforeunload

Precondition: You should be on Safari 10.

Hi, I'm have trouble getting the Leave | Stay confirmation box to show up on my page across different browsers.

Please go to https://www.biznessapps.com/cms, and login with following credentials:

username: [email protected]
password: skl@0!_~!(

After you've logged in, go to the /welcome page. Please click Settings in the left sidebar and go to the Membership tab.

If you can see "Enable Membership Features", then click it and change anything there and navigate to another page. You will see the confirmation box show up the first time you try to leave the page. onbeforeunload confirmbox

Click "Leave" to go to your target page, and then come back to this Settings page and try the same action; you won't see the confirmation box again (when using Safari).

I used this code snippet at: https://www.biznessapps.com/cms/v2/public/scripts/pages/settings.js?v=68.160720

/* settingsPages.isChanged() is my custom function */
window.addEventListener("beforeunload", function(event) {
    if (settingsPage.isChanged()) {
        event.returnValue = "some string";
        return "some string";
    }
});

It works fine on Google Chrome and Firefox, but not on Safari.

Thanks!

like image 931
Paul Z. Avatar asked Dec 02 '16 18:12

Paul Z.


People also ask

What triggers Onbeforeunload?

The beforeunload event is fired when the window, the document and its resources are about to be unloaded. The document is still visible and the event is still cancelable at this point. This event enables a web page to trigger a confirmation dialog asking the user if they really want to leave the page.

Can I use Onbeforeunload?

This feature is deprecated/obsolete and should not be used.

What is Onbeforeunload?

The onbeforeunload event occurs when the document is about to be unloaded. This event allows you to display a message in a confirmation dialog box to inform the user whether he/she wants to stay or leave the current page. The default message that appears in the confirmation box, is different in different browsers.


1 Answers

This is likely due to Safari's Back-Forward cache. A decent article on this can be found here: https://team.goodeggs.com/you-forgot-about-bfcache-f7a9bdeceb6c#.qgri9etsb

The fix is to basically just reload the page if it is loaded from the cache, like so:

window.onpageshow = function(event) {
    if (event.persisted) {
        window.location.reload() 
    }
};

event.persisted is the magic part. It is true if the page was loaded using the browsers "back" or "forward".

like image 131
mindfullsilence Avatar answered Oct 15 '22 10:10

mindfullsilence