3

I have requirement to handle events on browser like back, refresh and close on cross browser. The problem is my customer want a different logic for each of those events. For back button, this solution is quite fine:

but Now it's hard to distinguish between refresh and close, all solutions i found is about using of "beforeunload" event:

For refreshing by F5, i can catch event on keyboard, but when user press refresh button on browser, i can't. If i use "beforeunload", it is the same with close browser event.

I also found a workaround solution:

but unfortunately, what i want to do is showing message before page unload (show when browser is close but not when refreshing)

Does anyone know a solution for it (cross browser)

Thanks

uncle bob
  • 570
  • 1
  • 10
  • 21

2 Answers2

2

You might want to use Cookies/window.sessionStorage.

You can set a cookie without an explicit expiration date so that it is available only for the current session (which is valid till user closes the browser window).
You can also use sessionStorage object, it stores the data for only one session. The data is deleted when the user closes the specific browser tab.

You can follow this appraoch :
1.Create a cookie when user first visits the page document.cookie = "userloggedin=true"; OR set sessionStorage.userLoggedIn = true;

2.Cookie will be available after refresh/closing and reopening tab , if cookie is not present then it means user closed the window and re-opened it.
Similarly sessionStorage data will be deleted after user closes browser tab

Hope this helps !

Ankit
  • 5,733
  • 2
  • 22
  • 23
  • Hi @ankit_sharma i think localStorage will be better – uncle bob Aug 02 '17 at 09:00
  • i think sessionStorage will be better :P – Ankit Aug 02 '17 at 09:27
  • 1
    yes, it work for my case. on beforeunload i set flag isUnloadPage, and on load event i can get this flag so i can know user just refresh page, if user close browser, my load function will not work. somehow it's workaround solution. thanks – uncle bob Aug 07 '17 at 04:34
  • 1
    @Ankit I agree with you, sessionStorage data usually is deleted after the user closes the browser tab. BUT there is one exception. Data will not be deleted if user opened the browser after closing and has restored previously opened tabs. In this case session data is restored to the previous state! – Ihor Khomiak Feb 20 '21 at 15:17
0
tabOrBrowserStillAliveInterval;

constructor() {
  // do some action if the browser or last opened tab was closed (in 15sec after closing)
  if (this.wasBrowserOrTabClosed()) {
    // do some action
  }

  // every 15sec update browserOrTabActiveTimestamp property with new timestamp
  this.setBrowserOrTabActiveTimestamp(new Date());
  this.tabOrBrowserStillAliveInterval = setInterval(() => {
    this.setBrowserOrTabActiveTimestamp(new Date());
  }, 15000);
}

setBrowserOrTabActiveTimestamp(timeStamp: Date) {
  localStorage.setItem(
    'browserOrTabActiveSessionTimestamp',
    `${timeStamp.getTime()}`
  );
}

wasBrowserOrTabClosed(): boolean {
  const value = localStorage.getItem('browserOrTabActiveSessionTimestamp');

  const lastTrackedTimeStampWhenAppWasAlive = value
    ? new Date(Number(value))
    : null;
  const currentTimestamp = new Date();
  const differenceInSec = moment(currentTimestamp).diff(
    moment(lastTrackedTimeStampWhenAppWasAlive),
    'seconds'
  );

  // if difference between current timestamp and last tracked timestamp when app was alive
  // is more than 15sec (if user close browser or all opened *your app* tabs more than 15sec ago)
  return !!lastTrackedTimeStampWhenAppWasAlive && differenceInSec > 15;
}

How it works: If the user closes the browser or closes all opened your app tabs then after a 15sec timeout - an action that you expect will be triggered.

  • it works with multiple windows open
  • no additional load on the server
  • no problem with F5 / refresh

Browser limitations are the reason why we need 15sec timeout before logout. Since browsers cannot distinguish such cases: browser close, close of a tab, and tab refresh. All these actions are considered by the browser as the same action. So 15sec timeout is like a workaround to catch only the browser close or close of all the opened your app tabs (and skip refresh/F5).

Ihor Khomiak
  • 1,151
  • 11
  • 17