Javascript或angularjs推迟浏览器关闭或刷新之间关闭选项卡

时间:2015-01-28 16:24:50

标签: javascript angularjs browser event-handling dom-events

如果用户刷新页面或关闭浏览器/浏览器选项卡,有没有办法触发? (我想在AngularJS / JavaScript中触发它)。有什么想法吗?

现在我只知道当前页面关闭时使用以下代码:

var myEvent = window.attachEvent || window.addEventListener;
   var chkevent = window.attachEvent ? 'onbeforeunload' : 'beforeunload'; /// make IE7, IE8 compatable

   myEvent(chkevent, function (e) { // For >=IE7, Chrome, Firefox
       var confirmationMessage = ' ';  // a space
       (e || window.event).returnValue = "Are you sure that you'd like to close the browser?";
       return confirmationMessage;
   });

3 个答案:

答案 0 :(得分:1)

您的指令可能如下所示:

myApp.directive('myDirective', function() {
    return function($window) {
        var myEvent = $window.attachEvent || $window.addEventListener,
            chkevent = $window.attachEvent ? 'onbeforeunload' : 'beforeunload'; 

        myEvent(chkevent, function(e) {
            var confirmationMessage = ' ';
            (e || $window.event).returnValue = "Are you sure that you'd like to close the browser?";
            return confirmationMessage;
        });
    }
});

答案 1 :(得分:1)

link函数中绑定事件,该事件将允许访问angular编译的指令元素。

<强>指令

.directive('windowExit', function($window) {
  return {
    restrict: 'AE',
    link: function(element, attrs){
       var myEvent = $window.attachEvent || $window.addEventListener,
       chkevent = $window.attachEvent ? 'onbeforeunload' : 'beforeunload'; /// make IE7, IE8 compatable

       myEvent(chkevent, function (e) { // For >=IE7, Chrome, Firefox
           var confirmationMessage = ' ';  // a space
           (e || $window.event).returnValue = "Are you sure that you'd like to close the browser?";
           return confirmationMessage;
       });
    }
  };
});

<强> HTML

<body window-exit></body>

答案 2 :(得分:0)

我最终使用这种方法:

'use strict';
angular.module('myApp')
.controller('MyCtrl', ['$rootScope', '$scope', '$location', '$state', '$window', '$timeout', '$sce', 'UserAuthorize', function($rootScope, $scope, $location, $state, $window, $timeout, $sce, UserAuthorize) {

//Getting the value from storage
$window.sessionStorage.getItem('key');

//Setting the value to storage
$window.sessionStorage.setItem('key', 'value');

// Remove from storage
$window.sessionStorage.removeItem('key');

}]);

基于此,我在用户登录时保存了我的值。然后当浏览器窗口关闭时,值将不会持续存在。

通过使用本地存储,我只能将会话保留在当前窗口中。

编辑: 我虽然使用cookie方法我可以处理,但后来我遇到了区分刷新和关闭的问题。事实证明,localStorage节省了我的一天:)