Thangadurai Nainamalai
Thangadurai Nainamalai

Reputation: 189

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. But nowadays it's not working in all browsers.

Jquery sample Code:

'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. Is there any React library for the browser unload?

Thanks, Thangadurai

Upvotes: 2

Views: 15487

Answers (1)

Danny
Danny

Reputation: 3665

You can add and remove an event listener for the 'beforeunload' event within your componentDidMount and componentWillUnmount lifecycle functions.

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

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

Upvotes: 6

Related Questions