域内安全、永久保存。即客户端或浏览器中来自同一域名的所有页面都可访问localStorage数据且数据除了删除否则永久保存,但客户端或浏览器之间的数据相互独立。
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> </body> </html> <script type="text/javascript"> localStorage.setItem("coffeeType", "mocha"); //存储 var data = localStorage.getItem("coffeeType"); //读取 console.log(data); localStorage.removeItem("coffeeType"); //删除 var data2 = localStorage.getItem("coffeeType"); //读取 console.log(data2); localStorage.clear(); //清空保存的所有数据 localStorage.setItem("haha", "123"); //存储 </script>
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <button onclick="read();">读取</button> </body> </html> <script type="text/javascript"> function read(){ var data = localStorage.getItem("haha"); //读取 alert(data); } </script>