简体   繁体   English

在Javascript / AngularJS中检测/阻止浏览器关闭或会话存储卸载

[英]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? 如何使用javascript或AngularJS检测浏览器或选项卡的关闭,并允许用户通过对话框消息阻止它关闭?

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. 我有一个AngularJS应用程序,该应用程序将数据保存到会话存储中,以便用户可以刷新页面而不丢失其状态,并且还可以在不同选项卡中打开该应用程序的多个单独实例,而不必同步数据。

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. 注意1 :我需要使用会话存储,而不是本地存储,因为不同的选项卡需要是应用程序的独立实例,并且不能共享数据。

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. 注意2 :我已经尝试过unload和beforeUnload事件,但是这些事件不起作用,因为当单击“刷新”按钮或用户离开页面导航时,它们也会触发。 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. 注意3 :这是供公司内部使用的公司应用程序,我知道所有用户及其用例,因此我不担心会因弹出消息而使他们烦恼。 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. 理想情况下,您可以只使用beforeunload事件生命周期..但是正如您提到的,您不能。 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. 您可以为每个新会话创建一个哈希,然后将会话内容存储在本地存储中的该键下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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