延迟返回以等待异步功能(beforeunload事件) [英] Delay Return to Wait for Asynchronous Functions (beforeunload event)

查看:201
本文介绍了延迟返回以等待异步功能(beforeunload事件)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此编码示例中,函数 logout()不会执行所有异步调用,并且不会等到完成时才执行–而是在页面卸载之前,因为 beforeunload 事件触发页面的卸载.

In this coding example the function logout() won't execute all it's async calls and won't wait till they are finished – instead page is unloading before, because the return of the beforeunload event triggers unloading the page.

$(window).on('beforeunload', function(event) {
    event.preventDefault();
    logout();
    return;
});

我想尝试的是事件函数在 logout()中的几个异步调用完成后返回.

What I want to try is that the event function returns AFTER several asynchronous calls in logout() are finished.

我的目标是显示与此有关的警报!我只想在页面卸载之前执行一些代码.注销功能可能包含ajax请求和jQuery动画,这些动画的持续时间需要完成.

My goal is NOT to show an alert with this! I only want to execute some code before the page is unloaded. The logout function could contain ajax requests and jQuery animations with some duration that needs to be finished.

我尝试使用回调,但最终结果不理想,因为它返回的是回调,而不是事件函数.

I tried with callbacks, but end up with this, what isn't the desired result since it's returning to the callback, not to the event function.

$(window).on('beforeunload', function(event) {
    event.preventDefault();
    logout(function(x) { return; });
});

推荐答案

由于在页面卸载时在页面上执行的所有内容都将变为无效,因此您不能依靠页面本身来完成异步调用.

Since everything executed on the page would become invalid when the page is unloaded, you can't depend on the page itself to complete the async call.

chrome扩展名的一个替代方法是利用背景页面.您可以简单地在 beforeunload 处理程序中将消息发送到后台页面,捕获所有需要处理的信息,然后在后台页面中执行异步调用.示例代码为:

One wordaround for chrome extension would be making use of background page. You could simply send message to background page inside beforeunload handler, catching all info you need to deal with, and execute the async call in background page. Sample code would be:

content.js

content.js

window.addEventListener('beforeunload', function() {
    chrome.runtime.sendMessage({ info: "Here is the info you would like to pass to background page"});
});

background.js

background.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 将变得无效,请参见

Don't forget to return true from the event listener in background page, since chrome.runtime.onMessage.addListener would become invalid when the event listener returns, see this answer for more details.

这篇关于延迟返回以等待异步功能(beforeunload事件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆