title: Clear localStorage onbeforeunload
body: <p>I'm working with localStorage and I want to change a counter when closing the page. </p>
  
  <p>I found that <code>onbeforeunload</code> is the event which can be useful, so I decided to call my function in it. (<code>onunload</code> doesn't work for me in firefox/chrome)</p>
  
  <p>But when I try to call a function , it doesn't do anything. </p>
  
  <p>Is there any way to call a function when closing/refreshing a tab ?  </p>
  
  <pre><code>class MyLib{
     constructor(){
          window.onbeforeunload = function() {
              this._onClosePage();
          };
     }
  
      _onClosePage() {
          let openWindowsCount = this._getItem('countOpenWindow');
          openWindowsCount--;
          if (openWindowsCount === 0) {
              this._clearUp();
          }
      }
  
      _clearUp() { 
          this._removeItem('countPagesVisited');
      }
  }
  </code></pre>
  
  <p><strong>UPDATE</strong></p>
  
  <p>As suggested by <em>Oday</em> , I fixed the binding. But now , it works randomly.</p>
  
  <p>In chrome, it doesn't catch the refresh event, but sometimes it catches the exit. </p>
  
  <p>In firefox, it catches the exit, and randomly catches the refresh. </p>
  
  <pre><code>class MyLib{
     constructor(){
       document.getElementsByTagName('body')[0].onbeforeunload = this._onClosePage.bind(this);
     }
  
      _onClosePage() {
          let openWindowsCount = this._getItem('countOpenWindow');
          openWindowsCount--;
          if (openWindowsCount === 0) {
              this._clearUp();
          }
      }
      _onClosePage() { // call it once the page is closed or refreshed
          let openWindowsCount = localStorage.getItem('countOpenWindow');
          openWindowsCount--;
          localStorage.setItem('countOpenWindow' , openWindowsCount);
          if (openWindowsCount === 0) {
              this._clearUp();
          }
      }
      _clearUp() { 
          localStorage.removeItem('countOpenWindow');
      }
  }
  </code></pre>