Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
555 views
in Technique[技术] by (71.8m points)

dom - JavaScript question: Onbeforeunload or Onunload?

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 Javascript to detect the event and store the state of the page visit.

Now my predicament is: shall i use Onbeforeunload or Onunload method to accomplish this objective?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);    

}());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...