Safari: onbeforeunload

2020-07-10 07:15发布

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: pzheng64@gmail.com
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!

1条回答
兄弟一词,经得起流年.
2楼-- · 2020-07-10 07:41

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".

查看更多
登录 后发表回答