freaky freaky - 1 year ago 65
jQuery Question

jquery store array localstorage or cookie

I want to store an array in order to use it after a refresh page browser or with history forward (if my website is in the history).

This array is very important for me because it contains all my history urls of my visited website pages. It allows me to detect back and forward browser buttons.

for example I've got

history_url_array = [];
, how can I store it in local or in cookie easly and compatible with html4 and html5 without plugin script?

I success to do this kind of thing but just with a variable like this : window.location.pathname;

Sorry for my English, I'm French...

Answer Source

To set an array (in your case history_url_array) in localStorage, use

localStorage["history"] = JSON.stringify(history_url_array)

On page refresh, to get your array back from localStorage,

var history = JSON.parse(localStorage["history"])

But mind the browser support. IE has been shaky in its support for HTML 5 components. Here's the support table :

enter image description here

Anyway its better to run this function before you start using localStorage.

function supports_html5_storage() {
  try {
    return 'localStorage' in window && window['localStorage'] !== null;
  } catch (e) {
    return false;

If this function returns true you can insert your [] in localStorage, else, you'll have to store in a database or server session storage.

For more info on localStorage, head over to Dive Into HTML5