微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 如何防止角度4中的页面刷新

我想阻止页面刷新到处.

我试过下面的代码

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.';
      }
  }

}

尝试在ngOnChanges(),ngOnInit(),ngOnDestroy()甚至在组件类之外(抱歉不合逻辑),但没有任何作用?

我需要Angular或JavaScript中的解决方案而不是jQuery.

谢谢.

解决方法:

尝试以下订阅,在页面刷新时抛出警报窗口.在尝试刷新或关闭窗口之前,请执行一些用户事件,例如单击页面. 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
});

  }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐