我想在窗口关闭之前执行一些代码,但我不想显示提示。 这是我的代码:
$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/