简体   繁体   English

如何在关闭浏览器或窗口时触发Angularjs事件?

[英]How to Fire Angularjs Event when close browser or window?

I want to clear local storage values when user close browser or window tab using in angularjs. 我想在用户关闭浏览器或使用angularjs中的窗口选项卡时清除本地存储值。 I tried the following code. 我尝试了以下代码。

window.addEventListener("beforeunload", function (e) {
        var confirmationMessage = "\o/";
        alert("exit");
        (e || window.event).returnValue = confirmationMessage; //Gecko + IE
        return confirmationMessage;                            //Webkit, Safari, Chrome
    });

In the above code it asks the confirmation alert messages when refresh the page and also close the page. 在上面的代码中,它会在刷新页面时关闭确认警报消息并关闭页面。 But i want to fire angularjs event when close the browser/Window Tab only no need to ask the confirmation messages. 但是我想在关闭浏览器/ Window选项卡时激活angularjs事件,而不需要询问确认消息。

In the last project I worked on, I used the following code: 在我上一个项目中,我使用了以下代码:

$window.onbeforeunload = function (event) {
    if (self.form.$dirty) {
        return 'You have made changes, but you did not save them yet.\nLeaving the page will revert all changes.';
    }
}

First it performs a check to see if the data in the form has been changed. 首先,它会检查表单中的数据是否已更改。 If so, when the user tries to close the window or go to another url, a popup will be shown stating that there are unsaved changes. 如果是这样,当用户尝试关闭窗口或转到另一个URL时,将显示一个弹出窗口,指出存在未保存的更改。

So in this event you have access to the controller, so all angular events should be able to fire. 因此,在这种情况下,您可以访问控制器,因此所有角度事件都应该能够触发。

This one worked for me, but you need to pay attention that the custom message doesn't work in most of the browsers, (such as chrome, IE, firefox). 这个对我有用,但你需要注意自定义消息在大多数浏览器中都不起作用(例如chrome,IE,firefox)。

window.onbeforeunload = () => {
     return 'Are you sure you want to leave without saving?';
}

This will fired when the user refresh or close the tab or window, with the browser default message. 当用户使用浏览器默认消息刷新或关闭选项卡或窗口时,将触发此操作。

i have tried this code, it works for me! 我试过这段代码,对我有用!

      window.onbeforeunload = close;
                function close(){

                    // do something...
                    localStorage.clear();
                    sessionStorage.clear();
                   return null;
                }

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

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