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

373
Views
Logout user on refresh and close of browser

I am working in project using angular, i want to logout the user when user click on close button or refresh button. Below is the code

  document.addEventListener("DOMContentLoaded",function() {
      document.addEventListener('visibilitychange', function logData() {
          console.log(document.visibilityState)
        if (document.visibilityState == "hidden") {
          alert("hello")
         navigator.sendBeacon('logout');
        }
      });
    })

The problem is when user switches to some other tab in browser, this code executes and user logged out.

I researched on google and find beforeunlod event, but most of the answers saying its not working on mobile.

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

For refresh (or closing the tab, or closing the browser) we could listen for window:beforeunload to trigger logout. For a button it would be a simple (click) listener event. The onbeforeunload property of the WindowEventHandlers mixin is the event handler for processing beforeunload events. These events fire when a window is about to unload its resources. At this point, the document is still visible and the event is still cancelable.

@HostListener('window:beforeunload')
  unloadHandler(event) {
     alert("logging out now...")
     navigator.sendBeacon('logout');
  }

Docs: https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload#examples

about 4 years ago · Santiago Gelvez 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!