views:

480

answers:

5

Hi to everybody,

Is it possible to keep my (global) variables when the page is reloaded? If yes, how?

Thanks for any help. Best regards.

+1  A: 

The JavaScript environment will be reset when the browser leaves your page. However, you could register an onUnload handler to serialise your array to a cookie, then check for this every time the page is loaded and unserialise it if present.

Adam Wright
Hi Adam,What is happening when browser reset button is pressed?
Yusuf Akyol
I try to solve this problem without to use cookie.
Yusuf Akyol
+1  A: 

Does your browser have a reset button, or do you mean the reload button?

When the page loads, everything is loaded fresh. There is nothing left from any previous page. The only place to store anything that survives loading a page is in a cookie.

Note that the amount of data that you can put in cookies is limited to a few kilobytes per site. The exact limit varies from browser to browser, but you can't expect to be able to put more than perhaps a kilobyte or two worth of data in cookies.

Guffa
Yes reload button... Thanks too much Guffa... Best regards.
Yusuf Akyol
+2  A: 

You can persist data across page reloads via something like window.localStorage, window.sessionStorage (proprietary Mozilla extension) or database abstraction (window.openDatabase) provided by some of the WebKit -based browsers. See this article on MDC for a nice overview of Storage interfaces and this WebKit article on their database introduction.

kangax
Thanks too much Kangax... it's very interesting. Which browser's are Webkit-based?
Yusuf Akyol
ABrowse, Web Browser for Android, Arora, Google Chrome, Epiphany, iCab, Iris Browser, Midori, OmniWeb, rekonq, Safari, Shiira, Skipstone, Sputnik for MorphOS, SRWare Iron, Stainless, Sunrise, TeaShark, Web Browser for S60, WebOS : ) (See http://en.wikipedia.org/wiki/List_of_web_browsers#WebKit-based_browsers)
kangax
A: 

Are you talking about Cookies? If so you might want to review this open-source module:

http://www.openjsan.org/doc/b/bu/burak/HTTP/Cookies/1.11/

This will easily allow you to store cookies, that is data, even after a browser reload click. This makes doing it really easy and it is what I use.

var cookie = new HTTP.Cookies();
cookie.write('mydata', 'myvalue', '+1y');

//later on you can get that data EVEN AFTER a reload
var x = cookie.read('mydata');

You probably shouldn't try to make a cookies implementation from scratch though because it is very painful and you have to do a lot of testing across web browsers, such as to make sure Internet Explorer works.

jhuni
+1  A: 

In the same style you can store string values in the hash key.

Using the property:

window.location.hash = 'flight/105';

Then when refreshing the page you initialize back your variables.

Mic