pbhle
pbhle

Reputation: 2936

DIsplay popup when user refresh the page in angular 8

I want to show popup when user refresh/close tab in angular 8. I used candeactivate gaurd but its working when I change the route but not when I refresh/close the tab. Is there any way which will work for refresh,close tab event.

Upvotes: 1

Views: 3289

Answers (3)

Aman Kumar Gupta
Aman Kumar Gupta

Reputation: 3031

Confirmation Alert before browser reloads (i.e on reload of tab or on closing of tab)

This can also be done by using HostListener from angular core

EXAMPLE :

import { HostListener } from "@angular/core";

@HostListener("window:beforeunload", ["$event"]) unloadHandler(event: Event) {
    event.returnValue = false;
}

NOTE:

Chrome: v51, Firefox: v44, Safari: v9, Edge: Never Supported, Opera: v38

Thanks,

This may help you or somebody else :-)

Upvotes: 1

liza
liza

Reputation: 494

`<script type="text/javascript">
   window.onbeforeunload = function () {
  return 'Are you really want to perform the action?';
 }

`

add this in index.html

Upvotes: 0

yazantahhan
yazantahhan

Reputation: 3110

The only way you can do it by showing the default confirmation popup. It will ask the user if he's sure that he want to leave and discard the changes of not. This can be done by listening to the beforeunload event.

window.addEventListener('beforeunload', function (e) {
  // Cancel the event
  e.preventDefault(); // If you prevent default behavior in Mozilla Firefox prompt will always be shown
  // Chrome requires returnValue to be set
  e.returnValue = '';
});

You don't have the ability to customize the message, so it will show the default one for each browser.

Upvotes: 2

Related Questions