Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 275
Stephen Simpson Avatar asked Jan 28 '26 11:01

Stephen Simpson


1 Answers

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;
}
like image 149
phusick Avatar answered Jan 30 '26 00:01

phusick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!