根据 WHATWG 规范描述如下:
A mostly arbitrary limit of five megabytes per origin is recommended. Implementation feedback is welcome and will be used to update this suggestion in the future.
规范建议的本地数据存储不超过5M,同时大多数浏览器默认的localstorage存储大小也是5M限制。
localstorage大小限制可以通过以下面的代码进行测试:
var allocated = 5; var total = 0; for(var x in localStorage){ var amount = (localStorage[x].length * 2) / 1024 / 1024; total += amount; } var remaining = allocated - total; console.log( "Used: " + total + " MB"); console.log( "Remaining: " + remaining + " MB");
需要在localstorage中存储超过5M的数据时可以通过下面的方法来实现:
// 1. 将下面一行文件复制到你的文件中 !function(){function e(t,o){return n?void(n.transaction("s").objectStore("s").get(t).onsuccess=function(e){var t=e.target.result&&e.target.result.v||null;o(t)}):void setTimeout(function(){e(t,o)},100)}var t=window.indexedDB||window.mozIndexedDB||window.webkitIndexedDB||window.msIndexedDB;if(!t)return void console.error("indexDB not supported");var n,o={k:"",v:""},r=t.open("d2",1);r.onsuccess=function(e){n=this.result},r.onerror=function(e){console.error("indexedDB request error"),console.log(e)},r.onupgradeneeded=function(e){n=null;var t=e.target.result.createObjectStore("s",{keyPath:"k"});t.transaction.oncomplete=function(e){n=e.target.db}},window.ldb={get:e,set:function(e,t){o.k=e,o.v=t,n.transaction("s","readwrite").objectStore("s").put(o)}}}(); // 2. 存储值 ldb.set('nameGoesHere', 'value goes here'); // 3. 获取值 ldb.get('nameGoesHere', function (value) { console.log('And the value is', value); });