最终效果
// 从 window 对象中获取 localStorage
window.localStorage
window.localStorage.length
setItem
增加数据, 修改数据window.localStorage.setItem("userName", "昭昭")
window.localStorage.setItem("userName", "zhaoolee")
getItem
读取数据window.localStorage.getItem("userName")
removeItem
移除特定键的值window.localStorage.removeItem("userName")
clear
清除所有键的值window.localStorage.clear()
window.localStorage.key()
var storageLength = window.localStorage.length;
for(var i = 0; i < storageLength; i++) {
console.log(window.localStorage.key(i));
}
function onLocalStorageChange(event) {
console.log(event.key);
}
window.addEventListener('storage', onLocalStorageChange);
增删改查
事件,都会触发函数 onLocalStorageChange
增删改查
, 只有在其它页面(比如 B 页面)才能触发 onLocalStorageChange
实现的功能
<!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">
<link href="https://cdn.bootcss.com/twitter-bootstrap/4.1.3/css/bootstrap.css" rel="stylesheet">
<title>开始聊天</title>
</head>
<body>
<div style="margin: 30px;">
<div class="input-group" style="width: 500px">
<label style="height: 40px; line-height: 40px" for="user-name">用户名: </label><input type="text"
class="form-control" placeholder='请输入你的名字( 默认为“匿名用户” )' id="user-name" onblur="ChangeUserName(this)">
</div>
<!-- 存放 -->
<div id="chat-content" style="border: 1px solid #413F43; height: 300px; overflow: hidden; width: 600px;margin: 10px 0;padding: 10px;">
</div>
<div class="input-group" style="width: 600px">
<input type="text" class="form-control" placeholder="请输入需要发送的内容" id="my-input">
<span class="input-group-btn">
<button class="btn btn-primary" type="button" style="margin-left: 10px" id="btn"> 发 送 </button>
</span>
</div>
</div>
<script> //发送消息
var btn = document.getElementById("btn");
var myInput = document.getElementById("my-input");
var userName = document.getElementById("user-name").value || "匿名用户";
var chatContent = document.getElementById("chat-content");
// 获取当前的年月日,时分秒
function getDateTime() {
var dt = new Date();
var Year = dt.getFullYear();
var Month = dt.getMonth() + 1;
var Day = dt.getDate();
var Hours = dt.getHours();
var Minutes = dt.getMinutes();
var Second = dt.getSeconds();
return (Year + "-" + Month + "-" + Day + " " + Hours + ":" + Minutes + ":" + Second);
}
// 发送后存放到 session
btn.addEventListener("click", function () {
if (myInput.value != "") {
var dateTime = getDateTime();
var userNameAndInputvalue = userName + ":" + myInput.value;
// 将时间用户名和聊天内容写入 local storage
window.localStorage.setItem(dateTime, userNameAndInputvalue)
// 将时间用户名和聊天内容添加到页面中
chatContent.innerHTML = chatContent.innerHTML + "<div style='text-align: right'; border-bottom: 1px solid #413F43>" + dateTime+ "<br>" + userNameAndInputvalue +
"</div>"
myInput.value = "";
}
})
// 监听 session 变化时, 更新聊天信息
window.addEventListener('storage', function (e) {
if((e["key"] != null)&&(e["newValue"] != null)){
var userNameAndInputvalue = "<div>" + e["key"] + "<br>" + e["newValue"] + "</div>";
chatContent.innerHTML = chatContent.innerHTML + "<div style='text-align: left'>" + userNameAndInputvalue + "</div>"
}
})
// 绑定回车
document.onkeydown = function (e) {
if (e.keyCode === 13) {
btn.click();
}
}
// 重新输入用户名
function ChangeUserName() {
userName = document.getElementById("user-name").value || "匿名用户";
console.log("当前的用户名为:", userName);
} </script>
</body>
</html>
运行上面的聊天源码, 需要开启 http 服务, 可以参考 https://www.jianshu.com/p/f60758991e2d
博主前几天写网站,服务端向浏览器下发 cookies, 由于网络环境不太好, cookies 下发可能会失败, 博主最后用 Local Storage 代替了 cookies, 还是蛮好用的, 哈哈, 还是要主动拥抱新技术!