Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'beforeunload' event triggers when page is left in the background on Android

I'm trying to make a simple loading spinner that pops up when navigating. It shows up using a 'beforeunload' event when navigating away and uses the 'load' event to hide itself again when it is done.

The problem is that when I leave the page in the background on my phone for e.g. a few hours the 'beforeunload' event triggers and displays the spinner. Probably because Chrome on Android is partially unloading the page to save memory. The spinner doesn't go away by itself though and I can't seem to figure out how to make it disappear again in an elegant way.

Is there any other event I should be using instead?

    window.addEventListener("load", function() {
        topSpinner.classList.add("closed");
    });

    window.addEventListener("beforeunload", function() {
        topSpinner.classList.remove("closed");
    });
like image 216
Doskii Avatar asked Nov 27 '19 11:11

Doskii


People also ask

What triggers Beforeunload?

The beforeunload event is fired when the window, the document and its resources are about to be unloaded. The document is still visible and the event is still cancelable at this point. This event enables a web page to trigger a confirmation dialog asking the user if they really want to leave the page.

How do I turn off Beforeunload?

Cancelable: The beforeunload event can be canceled by user interaction: // by https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload#Example window. addEventListener("beforeunload", function(event) { event. preventDefault(); // Cancel the event as stated by the standard.

Which of the following events occurs before the browser unloads the document?

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

Chrome 68 (July 2018) introduced a new Page Lifecycle API: the state diagram supplied in this link does not show the System (browser) calling beforeunload before putting the page into the frozen state, but that is clearly what is happening.

Helpfully, the API introduced two new events that trigger as the page enters and exits this state: freeze and resume.

I've solved this problem on both mobile chrome and webview displays simply by adding this:

document.addEventListener('resume', (event) => {
  // The page has been unfrozen: remove the spinner if it's active
 topSpinner.classList.add("closed");
});
like image 180
mhepton Avatar answered Sep 22 '22 20:09

mhepton