Wednesday, June 13, 2012

Storing State in the Url Hash

It can be done. We have the technology.
function settingsToStorage(settings) {
    var s = [];
    $.each(settings, function (key, value) {
        s.push(key + "=" + encodeURIComponent(value));
    })
    return s.join("&");
}

function settingsFromStorage(storage) {
    var settings = {};
    storage.replace(/[#&]+([^=&]+)=([^&]*)/gi, function (m, key, value) { settings[key] = decodeURIComponent(value); });
    return settings;
}

2 comments:

  1. Nice one, I think ill use it!

    For anyone else stumbling onto this, you'll need to add a call to decodeURIComponent() in settingsFromStorage() when setting the value.

    ReplyDelete
  2. @Craig,
    Updated. Nice find, thanks.

    ReplyDelete