I am using Angular 7
and struggling to get browser home button click event.
Scenario:- When a user clicks on the Home button of the browser then I need to show confirmation message to the user asking if the user wants to save the changes or not. If "Yes"
then the user will stay on the current page and if clicks "No"
then redirect to the browser default page or may be route to some other page.
When I searched on google, most of the links I got are for browser back button which does not help in this scenario.
I have tried below solutions so far which are not working as It's unable to catch and hold of the handlers for Refresh and Home button.
1.
@HostListener("window:beforeunload", ["$event"]) unloadHandler(event: Event)
{
event.returnValue = false;
}
2.
//check for Navigation Timing API support
if (window.performance) {
console.info("window.performance works fine on this browser");
}
if (performance.navigation.type == 1) {
confirm('This is performance Api');
console.info( "This page is reloaded" );
} else {
console.info( "This page is not reloaded");
}
3.
this.router.events.subscribe((evt) => {
if (evt instanceof NavigationEnd) {
//trick the Router into believing it's last link wasn't previously loaded
this.router.navigated = false;
if (!this.router.navigated){
console.log(browserRefresh);
}
//if you need to scroll back to top, here is the right place
window.scrollTo(0, 0);
}
});
Please help.
I'm afraid the behaviour you are seeking is not possible. If it were possible to override the beforeunload
default behaviour (or similar) then malicious sites could trick users into thinking they have left a page when they have not.
In fact, it used to be possible to customise the message shown, but this feature was removed (in 2016) to prevent such scams: