On HTML
page, When user click / press F5
button page refresh but before refresh I want to execute one function or a simple alert.
User can click on refresh button, press F5
or Ctrl + R.
using Angular
2/4
The refresh of the page should trigger the event handler bound to window:beforeunload
. This stackblitz shows how to implement it for the "Home" component, using HostListener
. You can test the page refresh by executing it in full page mode.
import { Component, HostListener } from '@angular/core';
@Component({
...
})
export class HomeViewComponent {
@HostListener("window:beforeunload", ["$event"]) unloadHandler(event: Event) {
console.log("Processing beforeunload...");
// Do more processing...
event.returnValue = false;
}
...
}
You need to rely on browser events here.
window.onbeforeunload = (ev) => {
this.myFunction();
// OR
this.yuorService.doActon().subscribe(() => {
alert('did something before refresh');
});
// OR
alert('goin to refresh');
// finally return the message to browser api.
var dialogText = 'Changes that you made may not be saved.';
ev.returnValue = dialogText;
return dialogText;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With