实现原理:localStorage以及存储时的事件触发
实现环境:Chrome浏览器
注意:只能在同浏览器中跨标签页通讯
效果:
代码:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="box"></div>
<input type="text" id="inp" onkeypress="CheckInfo()">
<button onclick="sendMsg()">Send</button>
<br>
<input type="text" placeholder="input your name" id="myname">
<script>
var inp = document.getElementById("inp");
var box = document.getElementById("box");
var myname = document.getElementById("myname");
function CheckInfo() {
if (event.keyCode == 13) {
sendMsg();
}
}
function sendMsg() {
localStorage.setItem("msg", inp.value + "&&&" + myname.value);
box.innerHTML += "<div>" + myname.value + ": " + inp.value + "</div>";
inp.value = "";
}
window.addEventListener('storage', function (e) {
var value = localStorage.getItem("msg");
box.innerHTML += "<div>" + value.split("&&&")[1] + ": " + value.split("&&&")[0] + "</div>";
})
</script>
</body>
</html>
网友评论