【问题标题】:Angularjs Onbeforeunload without prompt not working properlyAngularjs Onbeforeunload 没有提示无法正常工作
【发布时间】:2016-10-24 08:40:15
【问题描述】:

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

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

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

返回 undefined 或 false 不起作用,因为我的代码没有被执行。 任何帮助表示赞赏。

【问题讨论】:

    标签: javascript angularjs onbeforeunload


    【解决方案1】:

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

    https://jsfiddle.net/8ubz4bxg/

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

    和你一样的控制器:

    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 方法可以做的事情是有限制的,因为一旦 unload 被提交,你做某事的时间就非常有限。要测试您有多少时间,您可以使用以下修改:

    $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 之类的值,您可能仍会在输出中看到“哈哈”。将其增加到 2 秒 (2000),您很可能看不到那条线。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多