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

dur*_*uru 4 javascript angularjs

我想在用户关闭浏览器或使用angularjs中的窗口选项卡时清除本地存储值.我尝试了以下代码.

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

在上面的代码中,它会在刷新页面时关闭确认警报消息并关闭页面.但是我想在关闭浏览器/ Window选项卡时激活angularjs事件,而不需要询问确认消息.

Koe*_*ren 7

在我上一个项目中,我使用了以下代码:

$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.';
    }
}
Run Code Online (Sandbox Code Playgroud)

首先,它会检查表单中的数据是否已更改.如果是这样,当用户尝试关闭窗口或转到另一个URL时,将显示一个弹出窗口,指出存在未保存的更改.

因此,在这种情况下,您可以访问控制器,因此所有角度事件都应该能够触发.


Gal*_*dil 5

这对我有用,但你需要注意,自定义消息在大多数浏览器(例如 chrome、IE、firefox)中不起作用。

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

当用户刷新或关闭选项卡或窗口时,将触发此事件,并显示浏览器默认消息。


Jav*_*all -1

我已经尝试过这段代码,它对我有用!

      window.onbeforeunload = close;
                function close(){

                    // do something...
                    localStorage.clear();
                    sessionStorage.clear();
                   return null;
                }
Run Code Online (Sandbox Code Playgroud)