$window.unload 中的 Post 方法从未调用更改 url,关闭选项卡,但在关闭浏览器时运行

Post method in $window.unload never called on change url, closing the tab, but ran on closing the browser

本文关键字:选项 运行 浏览器 url Post 中的 unload window 方法 调用      更新时间:2023-09-26

更改 URL 时永远不会调用我的解锁方法。关闭浏览器将执行该方法。关闭选项卡不会执行该方法...我得出这个结论是因为服务器端没有收到任何帖子(通过检查控制台(。

/* Callback function that unlocks the current time report when leaving the angular app */
    $window.onbeforeunload = function (event) {
        event.preventDefault();
        if ($scope.reportData != undefined && $scope.reportData.superId != undefined && !archive) {
            $http.post(Settings.timereportBaseURLhttp + 'monthlyreport/' + $routeParams.office + '/current/' + $routeParams.tmsstep + '/' + $scope.reportData.superId + '/unlock');
        }
    };

首先,除非$window指的是window,否则请尝试删除$。其次,event.preventDefault()不会阻止浏览器卸载窗口。在大多数浏览器中,它只会询问用户是否要离开页面。如果用户选择不停留在页面上,并且 AJAX 调用尚未完成,则浏览器可以立即关闭它,因此,您将不会在服务器端收到任何 POST 请求。

为了实现我认为您要做的事情,我会每隔一段时间 ping 服务器,如果服务器在合理的时间内没有收到 ping,我会解锁报告