localstorage 和sessionstorage的使用

localstorage 与sessionstorage的使用

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>storage的使用</title>
</head>
<body>
    <pre>
        <h1>storage的使用:localstorage 、sessionstorage</h1>
        localStorage:是为了解决cookie存储空间不足来解决的,一般浏览器存储空间大小为5M,在各个浏览器中可能不同
        localStorage的优势:
         1.突破了cookie 4k的限制,
         2. localStorage可以将第一次请求的数据存储到本地,这个5K存储在本地相当于本地的一个数据库,相比cookie可以节约存储
         localStorage的缺点:
         1.浏览器支持性不好,只有高版本浏览器支持
         2.localStorage会把本地存储的所有的数据都转换为string型
         3.localStorage在浏览器的隐藏模式是不显示的
         4.localStorage存储过多容易消耗空间
         5.localstorage 不会被爬虫抓到
         localStorage 与sessionstorage的区别:
         localStorage能永久本地化存储,sessionstorage会在会话结束消失。
         localStorage的增删改查
    
         ~~~JavaScript
         //增:
         localStorage['username'] = 'ghost'
         localStorage['passworld'] = 1223123,
         localStorage.tel = 138888888888,
         localStorage.setItem('email', 'ghostdot@163.com')
        // 删:
        localStorage.clear() //删除所有内容
        // 改:
        localStorage['username'] = 'ghost1'
         localStorage['passworld'] = 91223123,
         localStorage.tel = 138111111111118,
         localStorage.setItem('email', 'ghostdot@163.com')
         //查:
         localStorage['username'] 
         localStorage['passworld']
         localStorage.tel
         localStorage.getItem('username')
         ~~~
        localStorage 的注意事项:
         1.一般情况下我们会将json传入到localStorage中,但是localStorage存储的String对象,这时候就需要通过JSON.Stringfy这个方法来实现
         2.将Json字符串转换为json对象,通过JSON.Parse
        </pre>
         


     
    <script>
        console.log(localStorage)
        console.log(sessionStorage)
        localStorage['username'] = 'ghost'
        localStorage['passworld'] = 1223123,
        localStorage.tel = 138888888888,
        localStorage.setItem('email', 'ghostdot@163.com')
        console.log(localStorage.username)
        console.log(typeof(localStorage.passworld)) //string
        localStorage.removeItem('username') //删除username
        // localStorage.clear() //删除所有内容
        localStorage.getItem('username')
        for(var i=0;i<localStorage.length;i++){
                var key=localStorage.key(i);
                console.log(key); //localstorage 存储默认有一个key值从0开始
            }
            var data = {
                   car:'BMW',
                   color:"red",
                   wheel: 4,
                   seat:8

            }
            var j = JSON.stringify(data)
            console.log(j)
            localStorage.setItem('data', j) //key:data value:json对象
            var mydataString = localStorage.getItem('data')
             console.log("data:"+mydataString)
            var mydata = JSON.parse(mydataString)
            console.log(mydata)
    </script>

</body>
</html>
### Web Storage Mechanisms Comparison #### LocalStorage vs SessionStorage vs Cookies Characteristics LocalStorage, sessionStorage, and cookies are all methods of storing data on the client side but have distinct characteristics that define their use cases. - **Cookies**: Initially designed to store small pieces of data sent back and forth between a browser and server. Each cookie has a name-value pair along with attributes such as domain, path, expiration date, secure flag, etc. The size limit per cookie is around 4KB[^1]. When using JavaScript to set or get cookies, one must manually parse and serialize them since there's no built-in API specifically for this purpose. - **LocalStorage**: Provides a way to save larger amounts of structured data persistently (even after the browser window closes). It can hold up to about 5MB depending on browsers. Data stored here does not expire unless explicitly deleted by script or user action. Accessible via `localStorage` object which offers simple key-value operations like `.setItem()`, `.getItem()`[^2]. - **SessionStorage**: Similar to localStorage except it only retains information during the page session – meaning once you close the tab/window where your site was loaded from, everything gets wiped out automatically without needing any extra effort. Also supports similar capacity limits as localStorage[^3]. ```javascript // Example usage of each mechanism: // Setting items in localStorage/sessionStorage localStorage.setItem('key', 'value'); sessionStorage.setItem('anotherKey', JSON.stringify({ complex: true })); // Reading values back const valueFromLS = localStorage.getItem('key'); // returns "value" let parsedValueSS; try { parsedValueSS = JSON.parse(sessionStorage.getItem('anotherKey')); } catch(e) {} // Working with cookies through document.cookie string manipulation document.cookie = encodeURIComponent("name") + "=" + encodeURIComponent("John Doe"); console.log(document.cookie); // prints encoded version of our new cookie plus existing ones ``` --related questions-- 1. What security considerations should be taken into account when choosing among these storage options? 2. How do privacy policies impact how developers choose between localstorage, sessionstorage, and cookies? 3. Can you provide examples demonstrating best practices while handling sensitive data within web applications using these storages? 4. In what scenarios would someone prefer setting HTTP-only flags on cookies over utilizing DOM-accessible alternatives like localstorage or sessionstorage? 5. Are there performance implications associated with different types of web storage solutions mentioned above?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值