欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

浏览器cookie方式实现多页签通讯

程序员文章站 2022-06-23 08:27:38
index01.html 第一个页面改...

index01.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>第一个页面改</title>
</head>
<body>
    <input id="name" autocomplete="off">
    <input type="button" id="btn" value="提交">
    <script type="text/javascript">
        window.onload = function () {
            var btnEle = document.getElementById('btn');
            var nameEle = document.getElementById('name');
            btnEle.onclick = function () {
                var name = nameEle.value;
                document.cookie = "name=" + name; 
            }
        }
    </script>
</body>

</html>

index01.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>第二个页面</title>
</head>
<body>
    <script type="text/javascript">
        window.onload = function () {
            function getCookie(key) {
                // console.log(document.cookie.replace(/;\s+/gim, "\",\"").replace(/=/gim, "\":\""));
                if (document.cookie ) {
                    return JSON.parse("{\"" + document.cookie.replace(/;\s+/gim, "\",\"").replace(/=/gim, "\":\"") + "\"}")[key];
                } else {
                    return '';
                }
            }
            setInterval(function () {
                console.log("name=" + getCookie("name"));
            }, 5000);
        }
    </script>
</body>
</html>

 

本文地址:https://blog.csdn.net/weixin_43837268/article/details/109256351