Skip to content Skip to sidebar Skip to footer

Delay Return To Wait For Asynchronous Functions (beforeunload Event)

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 th

Solution 1:

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.

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

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

background.js

chrome.runtime.onMessage.addListener(function(request) {
    // The following is your async call
    logout();
    // Don't forget the following code
    return true;
});

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.


Solution 2:

Try using async/await for your handler, that is:

$(window).on('beforeunload', async function(event) {
    await logout();
    event.preventDefault();
    event.returnValue = false; // Seems require this for Chrome
});

Of course, you should have Promise returned from logout();

But I'm not sure if this is reliable.


Solution 3:

Not really a clean solution but you can try setTimeout to force the code to wait while the logout is in progress.

var timeToLogoutInMs = 500;
setTimeout(function() {
    // Nothing
}, timeToLogoutInMs);

EDIT: Why do you need to do this on the beforeunload hook? Why not set a manual option user to log out?


Post a Comment for "Delay Return To Wait For Asynchronous Functions (beforeunload Event)"