JavaScript question: Onbeforeunload or Onunload?

后端 未结 4 545
一整个雨季
一整个雨季 2020-12-05 07:47

So I want to store some information in localstorage of a browser when the page is refreshed or the user exits the page for future use. I figured that I\'d use some Javascrip

4条回答
  •  情深已故
    2020-12-05 08:12

    Why not register it with both just to be on the safe side? Just have the listener do a check to see if the data's stored yet and exit early.

    Here's a quick example using event properties:

    window.onunload = window.onbeforeunload = (function(){
    
      var didMyThingYet=false;
    
      return function(){
        if (didMyThingYet) return;
        didMyThingYet=true;
        // do your thing here...
      }
    
    }());
    

    Or you could use attachEvent:

    (function(){
    
      var didMyThingYet=false;
    
      function listener (){
        if (didMyThingYet) return;
        didMyThingYet=true;
        // do your thing here...
      }
    
      window.attachEvent("onbeforeunload", listener);
      window.attachEvent("onunload", listener);    
    
    }());
    

提交回复
热议问题