[SOLVED] How to Run a JavaScript Code at Browser Closing Time?

| | 1 min read

For a recent Drupal project there was a requirement to find the pages that a user visits on the site and send that to Google Analytics. Here, first we should save the page links that the user visits. But for this we need,

  • To know when a tab is closed
  • To know when a page is reloaded
  • To know when the browser is closed

In JS there is a browser close event onbeforeunload. In the onbeforeunload callback function enter your code before the return value. The onbeforeunload event sets a pop up box with a browser closing dialogue. The dialogue is the return value of callback function of onbeforeunload. If we put the return value to "null" then the popup box will not display at the browser closing time.

(function ($) {
    Drupal.behaviors.page_load_progress = {
      attach: function (context, settings) {
        window.onbeforeunload = close_event_function;
        function close_event_function() {
          //Enter your code before run window close;
          return null;
        }        
      }
    };
  }(jQuery));

The return value is very important in this onbeforeunload callback function. Hope this article helped :)