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



如果用户刷新页面或关闭浏览器/浏览器选项卡,有什么方法可以触发吗?(我想在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;
   });

您的指令可能如下所示:

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;
        });
    }
});

link函数中的绑定事件,该函数将提供对角度编译指令元素的访问。

命令

.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>

我最终使用了这种方法:

'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 方法我可以处理这个问题,但后来我遇到了区分刷新和关闭的问题。事实证明,本地存储节省了我的一天:)

相关内容

  • 没有找到相关文章

最新更新