跨浏览器文本存储 localStorage

用法:与 HTML5 的 localStorage 一致

浏览器本地存储测试Demo1:实现计数器

<script>
localStorage.lastname="Smith";
document.write(localStorage.lastname);
if (localStorage.pagecount){
    localStorage.pagecount=Number(localStorage.pagecount) +1;
}else{
    localStorage.pagecount=1;
};
document.write(" Visits: " + localStorage.pagecount + " time(s).");
</script>

刷新页面会看到计数器在增长。(放在域名下才起效,localhost也可以)
请关闭浏览器窗口,然后再试一次,计数器会继续计数。
localStorage 方法存储的数据没有时间限制。第二天、第二周或下一年之后,数据依然可用。

在客户端存储数据

HTML5 提供了两种在客户端存储数据的新方法:

之前,这些都是由 cookie 完成的。但是 cookie 不适合大量数据的存储,因为它们由每个对服务器的请求来传递,这使得 cookie 速度很慢而且效率也不高。

在 HTML5 中,数据不是由每个服务器请求传递的,而是只有在请求时使用数据。它使在不影响网站性能的情况下存储大量数据成为可能。

对于不同的网站,数据存储于不同的区域,并且一个网站只能访问其自身的数据。

HTML5 使用 JavaScript 来存储和访问数据。

浏览器本地存储测试Demo2:暂有问题,请移步Demo3

Press the SUBMIT button to store the value,
or press the RESTORE button to restore the stored value,
and press the CLEAR button to clear the localStorage data.

此处暂未设置函数调用,功能暂不可用,效果实质同Demo3.

<script>
//demo2 by sofish
typeof window.localStorage == 'undefined' && ~function () {

    var localStorage = window.localStorage = {},
        prefix = 'data-userdata',
        doc = document,
        attrSrc = doc.body,

        // save attributeNames to <body>'s `data-userdata` attribute
        mark = function (key, isRemove, temp, reg) {

            attrSrc.load(prefix);
            temp = attrSrc.getAttribute(prefix) || '';
            reg = RegExp('\\b' + key + '\\b,?', 'i');

            var hasKey = reg.test(temp) ? 1 : 0;

            temp = isRemove ? temp.replace(reg, '') : hasKey ? temp : temp === '' ? key : temp.split(',').concat(key).join(',');

            alert(temp);

            attrSrc.setAttribute(prefix, temp);
            attrSrc.save(prefix);

        };

    // add IE behavior support
    attrSrc.addBehavior('#default#userData');

    localStorage.getItem = function (key) {
        attrSrc.load(key);
        return attrSrc.getAttribute(key);
    };

    localStorage.setItem = function (key, value) {
        attrSrc.setAttribute(key, value);
        attrSrc.save(key);
        mark(key);
    };

    localStorage.removeItem = function (key) {
        attrSrc.removeAttribute(key);
        attrSrc.save(key);
        mark(key, 1);
    };

    // clear all attributes on <body> tag that using for textStorage
    // and clearing them from the
    // 'data-userdata' attribute's value of <body> tag
    localStorage.clear = function () {

        attrSrc.load(prefix);

        var attrs = attrSrc.getAttribute(prefix).split(','),
            len = attrs.length;

        if (attrs[0] === '') return;

        for (var i = 0; i < len; i++) {
            attrSrc.removeAttribute(attrs[i]);
            attrSrc.save(attrs[i]);
        };

        attrSrc.setAttribute(prefix, '');
        attrSrc.save(prefix);

    };

}();
</script>

问题及注意事项:

放在域名下才起效,localhost也可以

原理:

在支持 localStorage 的浏览器中直接使用 localStroage 的 API, 在不支持的 IE6 ~ IE7 中使用 USERDATA 来实现。具体参见源代码。

更多详情:HTML5 LocalStorage 本地存储

浏览器本地存储测试Demo3:

<script>
//demo3 by Martin Angelov
var Storage = function(win, doc){
    var hasSupport = true,
        store = win.localStorage,
        STORE_NAME = 'localstorage',
        obj,
        support = function (){ return hasSupport },
        error = function(){ throw new Error("don't support localStorage") };

    if (store && store.getItem){
        obj = {
            set : function(key, value){
                return store.setItem(key, value);
            },
            get : function(key){
                return store.getItem(key);
            },
            del : function(key){
                return store.removeItem(key);
            }
        };
    }else{
        store = doc.documentElement;
        try{
            store.addBehavior('#default#userdata');
            store.save(STORE_NAME);
        }catch(e){
            hasSupport = false;
        }
        if (hasSupport){
            obj = {
                set : function(key, value){
                    store.setAttribute(key, value);
                    store.save(STORE_NAME);
                },
                get : function(key){
                    store.load(STORE_NAME);
                    return store.getAttribute(key);
                },
                del : function(key){
                    store.removeAttribute(key);
                    store.save(STORE_NAME);
                }
            };

        }
    }
    if (!obj){
        obj = {
            set:error,
            get:error,
            del:error
        };
    }
    obj.support = support;
    return obj;
}(window, document);

/* example */
function load(){
    document.getElementById('txt').value = Storage.get('text');
}
function save(){
    var data = document.getElementById('txt').value;
    Storage.set('text', data);
}
function del(){
    Storage.del('text');
}
</script>