简体   繁体   中英

Detecting localStorage v sessionStorage objects in different browsers

I'm writing a Javascript class that is able to use either localStorage or sessionStorage. The selection of this is done on a class instance basis.

I have a method within this class, which receives the storage object as a parameter and runs an action according to the storage type (ie. local v session).

Eg.

function myMethod(store){
    // store: object storageObject
    //        The storage object being used (either
    //        sessionStorage or localStorage).

    if(store === sessionStorage){
        return sessionAction(store)
    }else if(store === localStorage){
        return localAction(store)
    }

    return null;
}

This does not work in Internet Explorer 8, producing the error: " Class doesn't support Automation ". It seems to work in other browsers quite well.

I've tried to get the object type (via Object.prototype.toString.call( store ) ) and test against that but IE8 always reports [object Object] for this. I managed to make some progress from the answer to Stackoverflow question: Weird IE8 internal [[ class ]] attribute behavior . This workaround gave me [object Storage] in IE.

However, I still cannot detect between the different storage types. Is there a simple methodology for detecting between the two types that works cross-browser?

I could rewrite it so the type has't to be supplied as a parameter to the method. However, I'd rather reduce the simplicity of the API by allowing users to simply supply the storage object.

You can go aggressive for the IE8 code branch (inspired by Modernizr ):

Compare storages:

function storagesEqual(testStorage, webStorage) {
    try {
        return testStorage === webStorage;
    } catch (ex) {
        // IE8 code branch
        var testKey = "storage-test";
        var testValue = (new Date()).valueOf().toString();
        var result = false;

        try {
            webStorage.setItem(testKey, testValue);
            if(testStorage[testKey] === testValue) {
                webStorage.removeItem(testKey);
                result = true;
            }
        } finally {
            return result;
        }
    }
}

Indetify storage type:

function storageType(store) {

    var STORAGE_LOCAL = 'local';
    var STORAGE_SESSION = 'session';
    var STORAGE_UNKNOWN = 'unknown';

    var localStorage = window.localStorage;
    var sessionStorage = window.sessionStorage;

    if(storagesEqual(store, localStorage)) return STORAGE_LOCAL;
    if(storagesEqual(store, sessionStorage)) return STORAGE_SESSION;
    return STORAGE_UNKNOWN;
}

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