Andy G
Andy G

Reputation: 19367

LocalStorage per page rather than (sub)domain?

localStorage is per domain/sub-domain, but I need to store and retrieve values per page.

Does anyone have an expression that removes the domain, bookmarks and query-string from the location? I can then use encodeURIComponent and prepend each localStorage-key with this value.

In which case, I also need the 'reverse' to this expression in order to retrieve values just for the current page. EDITED I don't think I need a 'reverse' function - it would be the same expression.

If I have the two expression above, would you use this (stripped) location as a single key-entry, and stringify all the values I need for the page within it? This might be preferable as I can just check the location once to discover if it has any corrresponding localStorage.

Upvotes: 3

Views: 1168

Answers (1)

jcolebrand
jcolebrand

Reputation: 16025

I have a function that generates a key for me, based on the page name (gotten from window.location) and appended with what the key would have been, then I store the data in localstorage.

function findPageName() {
    var path = window.location.pathname,
        s = path.split('/'),
        l = s.length,
        k = path.length,
        aux = 0;

    if (s[l - 1]) {
        return s[l - 1];
    } else if (l) { // l will always be a min of 2 (try '/'.split('/') )
        return s[l - 2];
    } else if (k == 0) {
        return '/'; //you likely want to replace this with another value
    } else {
        return s[1];
    }
}

function getKey(key) {
    return getPageName() + key;
}

Upvotes: 2

Related Questions