localStorage值的最大大小是多少

localStorage值的最大大小是多少

目前,localStorage仅支持字符串作为值,并且在存储到localStorage之前,对象需要转换为JSON字符串。使用本地存储存储的数据不会发送回服务器(不同于cookie)。所有数据都保留在客户端,因此对值的长度有明确定义的限制,根据所使用的浏览器,我们目前可以存储从 2 MB10 MB 的数据大小。

语法:

localStorage.setItem ( 'abc', 10 ); 
// this integer 10 gets converted to a string "10" 
// and then stored in localStorage variable named "abc".
JavaScript

示例: 此代码用于计算localStorage变量的大小。此JavaScript代码将通过不断增加长度的字符串来运行,直到浏览器引擎抛出异常为止。在此之后,它将清除测试数据,并在localStorage中设置一个大小键,用于存储localStorage的大小(以千字节为单位)。

<div> 
    localStorage limit in your Browser is 
    <span id="size">...</span> KBs. 
</div> 
<script> 
    //this script is to find the size of localStorage 
      
    function func1(num) 
    { 
        return new Array((num * 1024) + 1).join('a') 
    } 
      
    // Determine the size of localStorage if it's not set 
      
    if (!localStorage.getItem('size')) { 
    var i = 0; 
    try { 
        // Test up to 10 MB 
        for (i = 0; i <= 10000; i += 250) { 
            localStorage.setItem('test', func1(i)); 
        } 
        } catch (e) { 
        localStorage.removeItem('test'); 
        localStorage.setItem('size', i ? i - 250 : 0); 
        } 
    } 
          
    // when window is loaded this function is 
    // called and the size of localStorage is calculated 
    window.onload = function calculate(){ 
    var el = document.getElementById('size');     
    el.innerHTML = localStorage.getItem('size'); 
    } 
      
</script>
HTML

输出:

localStorage limit in your Browser is 5000 KBs.
JavaScript

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册