天天看點

使用LocalStorage、sessionStorage報異常DOMException: Failed to execute 'setItem' on 'Storage': 解決方法

本次項目需要用到前台緩存,使用了LocalStorage、sessionStorage

,但使用過程中報異常,原因及解決方法如下:

緩存到LocalStorage

​localStorage.setItem​

​方法儲存緩存對象。一般來說,隻要這一行代碼就能完成本步驟。但是LocalStorage儲存的資料是有大小限制的!我利用 chrome 做了一個小測試,儲存500KB左右的東西就會令 Resources 面闆變卡,2M 幾乎可以令到 Resources 基本卡死,到了 5M 就會超出限制,sessionStorage也是一樣的,浏覽器抛出異常:

DOMException: Failed to execute 'setItem' on 'Storage': Setting the value of 'xxxxx' exceeded the quota.

    at Error (native)

/**
                     * 把緩存對象儲存到localStorage中
                     * @param {string} key ls的key值
                     * @param {object} storeObj ls的value值,緩存對象,記錄着對應script的對象、有url、execute、key、data等屬性
                     * @returns {boolean} 成功傳回true
                     */
                    var addLocalStorage =function( key, storeObj ){
// localStorage對大小是有限制的,是以要進行try catch
// 500KB左右的東西儲存起來就會令到Resources變卡
// 2M左右就可以令到Resources卡死,操作不了
// 5M就到了Chrome的極限
// 超過之後會抛出如下異常:
// DOMException: Failed to execute 'setItem' on 'Storage': Setting the value of 'basket-http://file.com/ykq/wap/v3Templates/timeout/timeout/large.js' exceeded the quota
                        try{
                            localStorage.setItem( storagePrefix + key, JSON.stringify( storeObj ));
                            return true;
                        }catch( e ){
// localstorage容量不夠,根據儲存的時間删除已緩存到ls裡的js代碼
                            if( e.name.toUpperCase().indexOf('QUOTA')>=0){
                                var item;
                                var tempScripts =[];
// 先把所有的緩存對象來出來,放到 tempScripts裡
                                for( item in localStorage ){
                                    if( item.indexOf( storagePrefix )===0){
                                        tempScripts.push( JSON.parse( localStorage[ item ]));
                                    }
                                }
// 如果有緩存對象
                                if( tempScripts.length ){
// 按緩存時間升序排列數組
                                    tempScripts.sort(function( a, b ){
                                        return a.stamp - b.stamp;
                                    });
// 删除緩存時間最早的js
                                    basket.remove( tempScripts[0].key );
// 删除後在再添加,利用遞歸完成
                                    return addLocalStorage( key, storeObj );
                                }else{
// no files to remove. Larger than available quota
// 已經沒有可以删除的緩存對象了,證明這個将要緩存的目标太大了。傳回undefined。
                                    return;
                                }
                            }else{
// some other error
// 其他的錯誤,例如JSON的解析錯誤
                                return;
                            }
                        }
                    };