I want to prevent page refresh by everywhere.
I tried the code below
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { CommonServices } from '../services/common.service';
@Component({
selector: 'app-review-prescription',
templateUrl: './review-prescription.component.html',
styleUrls: ['../../assets/css/prescriptionView.css'],
providers:[
CommonServices
]
})
export class ReviewPrescriptionComponent implements OnInit {
constructor(
private commonServices:CommonServices,
private router:Router
){}
ngOnInit(){
window.onbeforeunload = function(event) {
return 'By refreshing this page you may lost all data.';
}
}
}
Tried this on ngOnChanges()
, ngOnInit()
, ngOnDestroy()
even outside the component class(sorry illogical) but nothing works?
I need solution in Angular or JavaScript not in jQuery.
Thanks.
unbind("keydown", disableF5); /* OR jQuery >= 1.7 */ $(document). off("keydown", disableF5); On a side note: This only disables the f5 button on the keyboard. To truly disable refresh you must use a server side script to check for page state changes.
The easiest way to reload current page without losing any form data in Javascript is to use the localStorage . JavaScript is one of the widely used programming languages by developers.
Try the below subscription to throw alert window on page refresh. do some user events like click over the page before trying to refresh or close the window. check the working version here
see the official documentation on beforeunload
ngOnInit() {
window.addEventListener("beforeunload", function (e) {
var confirmationMessage = "\o/";
console.log("cond");
e.returnValue = confirmationMessage; // Gecko, Trident, Chrome 34+
return confirmationMessage; // Gecko, WebKit, Chrome <34
});
}
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