1

How I can allow user's browser to actually leave page once beforeunload event is...

 3 years ago
source link: https://dev.to/pcmagas/how-i-can-allow-user-s-browser-to-actually-leave-page-once-beforeunload-event-is-fired-3ee9
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

How I can allow user's browser to actually leave page once beforeunload event is fired?

May 14

・1 min read

As I ask upon stackoverflow:
https://stackoverflow.com/q/67535677/4706711

I want once user confirms that wantr to leave a page to actually leave. The code so far is:

                    window.beforeunload = function(e){
                        var confirmAction = confirm("Wanna leave? This will BREAK the page.");
                        if(confirmAction){
                            //leavePage
                        }
                    };
Enter fullscreen modeExit fullscreen mode

But I do not know how I can allow user to leave once user accepts. Do you have any idea why?

Discussion (1)

pic

CollapseExpand

The beforeunload event is quite special due to security reasons. You can't launch a confirm inside this event, but there's a way to prompt the user if they want to leave, this is the code:

window.onbeforeunload = function(event) {
  event.preventDefault();
  event.returnValue = '';
}
Enter fullscreen modeExit fullscreen mode

This will make the browser ask the user if they really want to leave the page, and will unload the page if the user says Yes.

Comment button Reply


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK