Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent page refresh in angular 4

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.

like image 956
RajnishCoder Avatar asked Nov 16 '17 13:11

RajnishCoder


People also ask

How do I disable browser refresh button?

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.

How can I reload my current page without losing data?

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.


1 Answers

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
    });
}
like image 114
Prithivi Raj Avatar answered Oct 13 '22 01:10

Prithivi Raj