在此编码示例中,函数 logout()
不会执行所有异步调用,也不会等到它们完成 - 相反,页面会在之前卸载,因为 的返回>beforeunload
事件触发卸载页面。
$(window).on('beforeunload', function(event) {
event.preventDefault();
logout();
return;
});
我想尝试的是,事件函数在 logout()
中的几个异步调用完成后返回。
编辑:我的目标是不以此显示警报!我只想在页面卸载之前执行一些代码。注销函数可能包含 ajax 请求和需要完成一段时间的 jQuery 动画。
我尝试使用回调,但最终得到的结果是,这不是期望的结果,因为它返回到回调,而不是事件函数。
$(window).on('beforeunload', function(event) {
event.preventDefault();
logout(function(x) { return; });
});
最佳答案
由于页面卸载时,页面上执行的所有内容都会变得无效,因此您不能依赖页面本身来完成异步调用。
chrome 扩展的一个词是利用背景页面。您可以简单地将消息发送到 beforeunload
处理程序内的后台页面,捕获您需要处理的所有信息,并在后台页面中执行异步调用。示例代码为:
内容.js
window.addEventListener('beforeunload', function() {
chrome.runtime.sendMessage({ info: "Here is the info you would like to pass to background page"});
});
背景.js
chrome.runtime.onMessage.addListener(function(request) {
// The following is your async call
logout();
// Don't forget the following code
return true;
});
不要忘记从后台页面的事件监听器返回true,因为当事件监听器返回时chrome.runtime.onMessage.addListener
将变得无效,请参阅this answer了解更多详情。
关于javascript - 延迟返回等待异步函数(在卸载事件之前),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38057439/