简体   繁体   English

浏览器选项卡在 ReactJS 中关闭时如何触发弹出窗口?

[英]How to trigger popup when browser tab closes in ReactJS?

I have a enrollment form with some customer related information.我有一个包含一些客户相关信息的注册表。 If user form is half filled and the user is going to close the tab, then I'll trigger the popup with option of save and exit, exit.如果用户表单已填满一​​半并且用户将关闭选项卡,那么我将触发带有保存和退出选项的弹出窗口,退出。

I have some jQuery solution.我有一些 jQuery 解决方案。 But nowadays it's not working in all browsers.但是现在它不适用于所有浏览器。

Jquery sample Code: Jquery 示例代码:

'use strict';
$(document).ready(function() {

  $.fn.addEvent = function (obj, evType, fn) {
    if (obj.addEventListener) {
      obj.addEventListener(evType, fn, false);
      return true;
    } else if (obj.attachEvent) {
      var r = obj.attachEvent('on'+evType, fn);
      return r;
    } else {
      return false;
    }
  };

  $.fn.KeepOnPage = function (e) {
    var doWarn = 1;
    if (!e) {
      e = window.event;
    }
    if (!e) {
      return;
    }
    if (doWarn == 1) { // and condition whatever you want to add here
      e.cancelBubble = true;
      e.returnValue = 'Warning!\n\nNavigating away from this page will delete your text if you haven\'t already saved it.';
    }
    if (e.stopPropagation) {
      e.stopPropagation();
    }
  };

  $.fn.addEvent(window, 'beforeunload', $.fn.KeepOnPage);
});

But we need solution in ReactJS.但是我们需要 ReactJS 中的解决方案。 Is there any React library for the browser unload?是否有用于浏览器卸载的 React 库?

Thanks, Thangadurai谢谢,坦加杜赖

You can add and remove an event listener for the 'beforeunload' event within your componentDidMount and componentWillUnmount lifecycle functions.您可以在 componentDidMount 和 componentWillUnmount 生命周期函数中为“beforeunload”事件添加和删除事件侦听器。

https://facebook.github.io/react/docs/component-specs.html https://facebook.github.io/react/docs/component-specs.html

https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload

Example:示例:

...
componentDidMount() {
  window.addEventListener('beforeunload', this.keepOnPage);
}

componentWillUnmount() {
  window.removeEventListener('beforeunload', this.keepOnPage);
}

keepOnPage(e) {
  var message = 'Warning!\n\nNavigating away from this page will delete your text if you haven\'t already saved it.';
  e.returnValue = message;
  return message;
}
....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM