Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we detect when user closes browser?

Tags:

angular

I mean, I want to track when a user leaves the app, closing browser or tabs.

Components and Directives has a lifecycle hook called ngOnDestroy, which is called when the component is destroyed, but it can't catch when the user leaves the app

import { Component, OnInit } from '@angular/core';  @Component({   moduleId: module.id,   selector: 'app',   templateUrl: 'app.component.html' }) export class AppComponent implements OnDestroy {   constructor() { }    ngOnDestroy() {       alert(`I'm leaving the app!`);   }  } 

If the user closes the browser, the alert is not executed.

like image 901
chamberin Avatar asked Jun 05 '16 13:06

chamberin


People also ask

How do I know if browser or tab closed in react?

To handle the browser tab close even in React: Use the useEffect hook to add an event listener. Listen for the beforeunload event. The beforeunload event is triggered when the tab is about to be unloaded.

How do I stop a browser window from closing?

Use the Pin tab option to keep Prevent Close available in Chrome. To make this as painless as possible, I recommend pinning this website to your browser then moving the tab out of the way. To do that open Prevent Close, and then right-click the tab with your mouse. From the context menu select Pin tab.

How do I close a JavaScript browser?

JavaScript provides an in-built function named close() to close the browser window that is opened by using window. open() method.

How do I close my browser?

A. The procedure for closing all open Chrome browser tabs has changed over the years, but on most recent Android tablets, press down on the “x” on the end of any open tab. Leave your finger on the tab until the Close All Tabs option appears on screen and then select that option to shut down all of the open pages.


1 Answers

You can listen to the unload or beforeunload events like this:

export class AppComponent {   @HostListener('window:unload', [ '$event' ])   unloadHandler(event) {     // ...   }    @HostListener('window:beforeunload', [ '$event' ])   beforeUnloadHandler(event) {     // ...   } } 

See also

  • Detect browser or tab closing
  • https://developer.mozilla.org/en-US/docs/Web/API/Window/unload_event
like image 110
Günter Zöchbauer Avatar answered Sep 21 '22 06:09

Günter Zöchbauer