javascript - 如何等待浏览器关闭直到服务器调用完成?

标签 javascript angularjs ajax http browser

我正在尝试调用一项在浏览器关闭或选项卡关闭时更新数据的服务。问题是使用 $http 的服务调用及其异步,因此根据我的浏览器卸载事件取消该调用并关闭浏览器。我希望浏览器等到我收到该服务调用的响应/错误。

我尝试调用 e.preventDefault()e.stopPropagation() 但它不起作用。

function releaseDocument(e) {
    EventService.releaseDocument().then(function() {
        window.close();
    }, function() {
        window.close();
    });
}

$window.onbeforeunload = releaseDocument;
$window.onunload = releaseDocument;

任何人都可以帮助或建议任何替代方案来实现同样的目标!?

最佳答案

也许我们可以通过使用同步 AJAX 调用来实现,这只是我的建议。


We will show a confirmation box when you close browser/tab. at this same time we will call your service synchronously. But we should call this service before execute the confirm box line. So sync call will execute every line and return the result then only the confirmation will fire/ or close the tab. Si here we have few time to execute the function.


 window.addEventListener("beforeunload", function (e) {
  var confirmationMessage = "Do you want close this browser";    
   releaseDocument()// it should be an sync function ( like you can set async:false in your ajax options 

  (e || window.event).returnValue = confirmationMessage; //Gecko + IE
  return confirmationMessage;                            //Webkit, Safari, Chrome
});

关于javascript - 如何等待浏览器关闭直到服务器调用完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41437346/

相关文章:

AngularJs:ui.router 未加载 Controller

ajax - ASP.NET MVC 4 - Ajax.BeginForm 和 html5

javascript - div 应使用 jquery 和 ajax 每三秒刷新一次

javascript - 使用 Javascript not 运算符时出现奇怪的结果

c# - 日期验证

javascript - Vue.js 在组件/应用程序之外观察 DOM 元素属性

twitter-bootstrap - 使用 AngularJS 和模式对话框清理 URL

javascript - npm install package-name 非常慢

javascript - 是否可以获取一个巨大的字符串并将其作为 JavaScript 通过 URL 路径加载?

asp.net-mvc - 从 Ajax 表单帖子内重定向