Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 the beforeunload event triggers unloading the page.

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

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

EDIT: 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; });
});
like image 969
ScientiaEtVeritas Avatar asked Sep 16 '25 18:09

ScientiaEtVeritas


1 Answers

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.

like image 162
Haibara Ai Avatar answered Sep 18 '25 08:09

Haibara Ai