gpt4 book ai didi

javascript - 浏览器在 "PageUnload"& new "PageLoad"之后继续执行 Javascript

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:45:26 24 4
gpt4 key购买 nike

我们有以下 AJAX 调节器。这是为了能够对一个页面执行许多(20 多个)ajax 请求而不会因为第一个 X 请求总共花费 60 秒而导致剩余超时。

RequestThrottler: {
maximumConcurrentRequests: 3, //default to 3
requestQueue: new Array(),
numberOfRequestCurrentlyProcessing: 0,

addRequestToQueue: function (currentRequest) {
var self = this;
self.requestQueue.push(currentRequest);

if (self.numberOfRequestCurrentlyProcessing < self.maximumConcurrentRequests) { self.sendNextRequest(); }
},

sendNextRequest: function () {
var self = this;
if (self.numberOfRequestCurrentlyProcessing >= self.maximumConcurrentRequests) { return; }
if (self.requestQueue.length === 0) { return; }

var currentRequest = self.requestQueue.pop();
self.numberOfRequestCurrentlyProcessing++;
AJAX.SendAjaxRequest(currentRequest.url, currentRequest.httpMethod,
function(data){
self.numberOfRequestCurrentlyProcessing--;
currentRequest.onSuccessCallback(data);
self.sendNextRequest();
},
function(){
self.numberOfRequestCurrentlyProcessing--;
currentRequest.onErrorCallback();
self.sendNextRequest();
});
},

sendUpdateRequest: function (currentRequest) {
var self = this;
self.addRequestToQueue(currentRequest);
}
}

但是,由于这些请求位于 Javascript 队列中,因此当用户尝试加载新页面时,开发人员工具会在新页面的 NET 区域中显示响应。出于隐私原因,我们的应用程序进行了检查,不允许这种行为。这对浏览器来说是正常的,还是某种错误,或者我做错了什么?

最佳答案

一个干净的解决方案是监听 window.onbeforeunload 事件以abort 任何尚未收到响应的 ajax 请求。

应该使用 beforeunload 事件而不是 unload ,原因如下:

1) beforeunload 事件比unload 事件更可靠:

The exact handling of the unload event has varied from version to version of browsers. For example, some versions of Firefox trigger the event when a link is followed, but not when the window is closed. In practical usage, behavior should be tested on all supported browsers, and contrasted with the proprietary beforeunload event.

来源:

2) beforeunload事件可以取消,而unload事件不能取消。如果您想在 beforeunload 事件发生时提示用户,这将为您提供灵 active 。确认将询问用户是否要继续导航到另一个页面,或者他们是否要取消,因为并非所有 ajax 请求都已完成。

window.addEventListener("beforeunload", function (e) {
var confirmationMessage = "\o/";

(e || window.event).returnValue = confirmationMessage; // Gecko and Trident
return confirmationMessage; // Gecko and WebKit
});

来源:

关于javascript - 浏览器在 "PageUnload"& new "PageLoad"之后继续执行 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28705634/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com