简体   繁体   中英

Detect/Prevent Browser Close or Session Storage Unload in Javascript/AngularJS

How can I use javascript or AngularJS to detect the browser or tab closing and allow the user to prevent it through a dialog message?

I have an AngularJS app that saves data to session storage so that the user can refresh the page without losing their state and also have multiple separate instances of the app open in different tabs without having to sync data.

If the user closes the tab or browser then they lose their work in progress because the session is unloaded. I want to detect when the session is being destroyed and show a message to the user that informs them they will lose their work in progress if they proceed and allow them to select OK to continue closing the browser/tab or cancel to stop prevent it from closing. I only want to show the message on browser/tab close, not when the user hits the refresh button or navigates to a new page.

Note 1 : I need to use session storage and not local storage because different tabs need to be isolated instances of the app and cannot share data.

Note 2 : I've tried the unload and beforeUnload events but these don't work because they also fire when the refresh button is clicked or the user navigates away from the page. I only want to show the message before the session is destroyed, ie when the tab/browser is actually closed.

Note 3 : This is a corporate app for internal company use and I know all the users and their use cases so I am not worried about annoying them with the popup message. I realize that preventing a user from closing the app would be a bad user experience on a public website but his is a very controlled scenario.

Ideally you could just use the beforeunload event lifecycle.. but as you mentioned you can't. From what I know, there is no other way to bind a method to a similar event.

That said, you might also want to reconsider your first note. You could create a hash for each new session, and store the session stuff under that key in localstorage.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM