Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the limitation using before unload event?

What is and what is not possible to do inside the beforeunload callback ?

Is it possible to open an XHR/fetch and send data to the server ? If no, is it possible to just send data, without any success callback blocking ?

Is it possible to change the location of the page with window.location? How long does the function continue to execute?

window.addEventListener("beforeunload", function (event) {
    // code
});
like image 615
Walle Cyril Avatar asked Jan 28 '17 11:01

Walle Cyril


People also ask

What is the difference between unload and Beforeunload?

beforeunload event – the user is leaving: we can check if the user saved the changes and ask them whether they really want to leave. unload – the user almost left, but we still can initiate some operations, such as sending out statistics.

Which event occurs when the page has been unloaded?

The onunload event occurs once a page has unloaded (or the browser window has been closed). onunload occurs when the user navigates away from the page (by clicking on a link, submitting a form, closing the browser window, etc.).


1 Answers

You can put anything you want inside of a "beforeunload" callback, you're just not guaranteed it will execute unless you use synchronous/blocking code.

Here's a blocking sleep function I'll use for demonstration purposes:

function sleep(delay) {
  var start = new Date().getTime();
  while (new Date().getTime() < start + delay);
}

Any synchronous, blocking code is guaranteed to execute to completion:

window.addEventListener("beforeunload", function (event) {
  console.log("Blocking for 1 second...");
  sleep(1000);
  console.log("Done!!");
});

Any async code (i.e. code with callbacks) like the code below will be queued on the event loop, but it may or may not finish executing depending on when your browser completes the "unload" action (e.g. close window, refresh page.) The time here really depends on your computer's performance. On my computer, for example, a timeout of 10ms with log statement still executes because my browser hasn't had time to refresh/close the page.

window.addEventListener("beforeunload", function (event) {
  setTimeout(() => {
    console.log("Timeout finished!"); // Odds are this will finish
  }, 10);
  console.log("Done!!");
});

A timeout of 100ms, however, is never executed:

window.addEventListener("beforeunload", function (event) {
  setTimeout(() => {
    console.log("Timeout finished!");
  }, 100);
  console.log("Done!!");
});

The only way to guarantee your function will run to completion is to make sure you're writing synchronous code that blocks the event loop as in the first example.

like image 146
fny Avatar answered Sep 21 '22 07:09

fny