简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM