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

时间:2016-07-29 05:22:00

标签: javascript jquery reactjs typescript ecmascript-6

我有一份注册表,其中包含一些与客户相关的信息。如果用户表单已填满一​​半且用户要关闭选项卡,则会选择“保存并退出”退出弹出窗口,然后退出。

我有一些jquery解决方案。但现在有一天它并不适用于所有浏览器。

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);
});

但我们需要在reactjs中解决。是否有任何反应库供浏览器卸载?

谢谢, Thangadurai

1 个答案:

答案 0 :(得分:4)

您可以添加和删除事件监听器,以便' beforeunload' componentDidMount和componentWillUnmount生命周期函数中的事件。

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

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

示例:

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