Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

252
Views
I need JavaScript (Angular) event listener for closing page and tabs

I need event that will work on closing page or tab, but also will not trigger on refreshing page. I know for "beforeunload", but that still work on refreshing page.

Here is my code

@HostListener('window:beforeunload', ['$event'])
checkIsUserLogOut() {
    if (ConfigurationModel.applicationOptions.autoLogOutWhenWebBrowserClosed) {
        localStorage.removeItem('auth_token');
        localStorage.removeItem('auth_token_expires_on');
    }
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Found an article for this exact problem (does not want to trigger code on refresh).

It uses a localStorage variable to save the datetime of the last unload event, and if its less than a preset amount of time it considers it a refresh.

the unload event handler:

function unload(event) {
    if (window.localStorage) {
        // flag the page as being unloading
        window.localStorage['myUnloadEventFlag']=new Date().getTime();
    }

    askServerToDisconnectUserInAFewSeconds(); // synchronous AJAX call

}

on page load:

function myLoad(event) {
    if (window.localStorage) {
        var t0 = Number(window.localStorage['myUnloadEventFlag']);
        if (isNaN(t0)) t0=0;
        var t1=new Date().getTime();
        var duration=t1-t0;
        if (duration<10*1000) {
            // less than 10 seconds since the previous Unload event => it's a browser reload (so cancel the disconnection request)
            askServerToCancelDisconnectionRequest(); // asynchronous AJAX call
        } else {
            // last unload event was for a tab/window close => do whatever
        }
    }
} 

Hope it helps.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!