Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
195
rated 0 times [  197] [ 2]  / answers: 1 / hits: 17454  / 14 Years ago, thu, september 23, 2010, 12:00:00

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?


More From » dom

 Answers
9

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

}());

[#95530] Tuesday, September 21, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
blaisep

Total Points: 748
Total Questions: 95
Total Answers: 108

Location: Federated States of Micronesia
Member since Sun, May 16, 2021
3 Years ago
blaisep questions
Wed, Dec 16, 20, 00:00, 4 Years ago
Sun, Aug 16, 20, 00:00, 4 Years ago
Tue, Nov 12, 19, 00:00, 5 Years ago
Mon, Nov 11, 19, 00:00, 5 Years ago
;