javascript - Angularjs Onbeforeunload 无提示无法正常工作

标签 javascript angularjs onbeforeunload

我想在窗口关闭之前执行一些代码,但我不想显示提示。 这是我的代码:

  $window.onbeforeunload = function(){
        $rootScope.$broadcast('war-change');
        return undefined;
    };

    $scope.$on('war-change',function(){
        console.log('here');
         //Execute some more code here.
        });

返回未定义或错误不起作用,因为我的代码没有被执行。 如有任何帮助,我们将不胜感激。

最佳答案

您的代码确实按预期工作。检查以下 fiddle :

https://jsfiddle.net/8ubz4bxg/

<div ng-app>
  <h2>Test unload</h2>
  <div ng-controller="unloadCtrl">
  </div>
</div>

Controller 与您相同:

function unloadCtrl($scope,$window,$rootScope) {
   $window.onbeforeunload = function(){
        $rootScope.$broadcast('war-change');
        return undefined;
    };

    $scope.$on('war-change',function(){
        console.log('here');
         //Execute some more code here.
        });
}

但是,使用 beforeunload 方法可以执行的操作是有限制的,因为一旦提交卸载,您执行操作的时间就非常有限。要测试您有多少时间,可以使用以下修改:

$scope.$on('war-change',function(){
    console.log('here');
     //Execute some more code here.
     setTimeout(function(){ console.log("ha-ha")}, 100)
     console.log("he-he")
    });

现在,如果您将超时减少到 0-100 之类的值,您可能仍然会在输出中看到“ha-ha”。将其增加到 2 秒 (2000),您很可能不会看到该行。

关于javascript - Angularjs Onbeforeunload 无提示无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40214047/

相关文章:

javascript - 将自定义函数注入(inject) onclick 事件

ajax - 使用 Angular js 登录 ajax 后清空 Passport session

javascript - 浏览器后退按钮和 javascript

javascript - 在 Coffeescript 中加载 AJAX 后处理图像大小

javascript - 悬停时我的 h1 标签链接出现下划线,我没有添加

javascript - AngularJS - ui-bootstrap 分页 "show more results"不起作用

javascript - 将数组值绑定(bind)到 AngularJs 中的下拉列表

javascript - 当用户决定在 onbeforeunload 事件后留下时执行操作

jquery - 在页面卸载/浏览器关闭之前运行动画

javascript - 如何使用 jQuery 删除文本区域的禁用属性?