How to trigger popup when browser tab closes in ReactJS?

11,738

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;
}
....
Share:
11,738
Thangadurai Nainamalai
Author by

Thangadurai Nainamalai

Updated on June 14, 2022

Comments

  • Thangadurai Nainamalai
    Thangadurai Nainamalai almost 2 years

    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

  • loganfsmyth
    loganfsmyth over 7 years
    Note, Chrome no longer uses the text returned, it shows a generic message saying changes may not be saved.
  • Thangadurai Nainamalai
    Thangadurai Nainamalai over 7 years
    This before unload function work in all browser like safari, chrome, firefox, opera and so on