JavaScript question: Onbeforeunload or Onunload?

后端 未结 4 536
一整个雨季
一整个雨季 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:06

    The proper place to do it is onunload. onbeforenload is meant to be used when you may need to stop the user from leaving the page, like when there is unsaved data.

    I would be weary of writing code to cover all cases because you're not willing to test all cases. If you do your research and find that's it's too complicated across browsers, yeah, go ahead and do as much as you can. However, I believe there is no problem with doing local storage onunload. I actually did run into a problem, trying to send information to the server onunload. That did not happen reliably across browsers so I did end up with an approach that used both unload and beforeunload, but only after due diligence.

    So my suggestion is do it onunload, check all your browsers.

    0 讨论(0)
  • 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);    
    
    }());
    
    0 讨论(0)
  • 2020-12-05 08:28

    From my experience: use onunload since Opera does not support the other event. Yes, I know... Opera... but still :)

    0 讨论(0)
  • 2020-12-05 08:31

    I believe that Onbeforeunload is a safe bet. It is possible for browser to not execute onunload script completely - for example, if you have alert in onunload, chrome would not show if you close the window.

    0 讨论(0)
提交回复
热议问题