Onbeforeunload event in Android Chrome doesn't get fired

263 Views Asked by At

I need to save my session token in localStorage in order to get it back when user reloads the page:

window.addEventListener('beforeunload', this.savetoken.bind(this));
window.addEventListener('unload', this.savetoken.bind(this));

function async savetoken() {
    const token_ = await this.getToken();
    localStorage.setItem('sbk:token', token_);
    console.log('token saved in storage!!!', token_);
}

In desktop Chrome this work's perfectly, but in mobile versione (Android Chrome 85) the unload/beforeunload event doesn't get fired when closing browser or tab, it works only when refreshing the page.

Is there a way to get around this?

1

There are 1 best solutions below

1
On

As https://developer.chrome.com/blog/page-lifecycle-api/#the-unload-event says

Many developers treat the unload event as a guaranteed callback and use it as an end-of-session signal to save state and send analytics data, but doing this is extremely unreliable, especially on mobile! The unload event does not fire in many typical unload situations, including closing a tab from the tab switcher on mobile or closing the browser app from the app switcher.

You can try visibilitychange and/or pagehide events to save data. And as a fallback you can save data periodically, e.g. once in a minute via setInterval().