实现Tab页之间通信的方式

5 种方式:

  1. localstorage
  2. webworker
  3. web-socket
  4. cookie
  5. postMessage

localstorage

先看效果:


test3.gif

代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
    <style>
        #div1 {
            width: 200px;
            height: 200px;
            background-color: red;
        }
    </style>
    <title>Document</title>
</head>
<body>
    <button id="button">Click me.</button>
    <script>
        jQuery("#button").on('click', () => {
            window.localStorage.setItem('a', Math.random())
        })
        window.addEventListener('storage', e => {
            console.log(e)
        })
    </script>
</body>
</html>

webWorker

先看效果:


test1.gif

看代码:


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
    <style>
        #div1 {
            width: 200px;
            height: 200px;
            background-color: red;
        }
    </style>
    <title>Document</title>
</head>
<body>
    <button id="button1">send</button>
    <button id="button2">get</button>
    <script>
        let worker;
        if (typeof Worker === "undefined") {
            alert('当前浏览器不支持webworker')
        } else {
            worker = new SharedWorker('work.js', 'work2');
 worker.port.onmessage = function(e) {
                console.log(`获得worker的数据:${e.data}`)
            }
        }
        jQuery('#button1').on('click', () => {
            let data = parseInt(Math.random() * 10)
            console.log(`发送数据:${data}`)
            worker.port.postMessage(data);
        })
        jQuery('#button2').on('click', () => {
            worker.port.postMessage('get');
        })
    </script>
</body>
</html>
//work.js
let data1 = '';
this.onconnect = function(e) {
    console.log('e', e);
    let port = e.ports[0];
    port.onmessage = function(e) {
        if(e.data === 'get') {
            port.postMessage(data1)
        }else {
            data1 = e.data
        }
    }
}

web-socket

先看效果:


test0.gif

客户端代码(web)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
    <style>
        #div1 {
            width: 200px;
            height: 200px;
            background-color: red;
        }
    </style>
    <title>Document</title>
</head>
<body>
    <button id="button1">send</button>
    <button id="button2">get</button>
    <script>
        let ws = new WebSocket("ws://localhost:3009");
        ws.onopen = function(e) {
            console.log("Connection open ...");
            // ws.send("Hello WebSockets!");
        };
        ws.onmessage = function(e) {
            console.log(`收到数据${e.data}`);
            // ws.close();
        };
        ws.onclose = function(evt) {
            console.log("Connection closed.");
        };
        jQuery('#button1').on('click', () => {
            let data = parseInt(Math.random() * 10);
            console.log(`发送数据${data}`);
            ws.send(data)
        })
    </script>
</body>
</html>

服务端代码(koa)

const Koa = require('koa');
const serve = require('koa-static')
const path = require('path')
const Router = require('koa-router');
const websocket = require('koa-websocket')
const home = serve(path.resolve(__dirname, './'))
const app = websocket(new Koa());
let ctxs = new Set();//保证websocket唯一性
app.ws.use(function(ctx, next) {
    ctxs.add(ctx);
    ctx.websocket.on('message', function(message) {
        ctxs.forEach((item, index , arr) => {//客户端每新建一个websokcet就会保存到这个ctx中,每个ctx中的websokcet是独立的
            item.websocket.send(message)
        })
    });
    ctx.websocket.on('close', function(message) {
        ctxs.delete(ctx)
    })
    next(ctx)
} )
const router = new Router()
router.get('*', (ctx, next) => {
    ctx.body = 'hello world';
})
app.use(home)
app.use(router.routes())
    .use(router.allowedMethods());
app.listen(3009, () => {
    console.log('server is started at port 3009')
})

cookie

将要传递的信息存储在cookie中,每隔一定时间读取cookie信息,即可随时获取要传递的信息。

页面1:
<input id="name">  
<input type="button" id="btn" value="提交">  
<script type="text/javascript">  
    $(function(){    
        $("#btn").click(function(){    
            var name=$("#name").val();    
            document.cookie="name="+name;    
        });    
    });    
</script>  

页面2:

<script type="text/javascript">  
    $(function(){   
        function getCookie(key) {    
            return JSON.parse("{\"" + document.cookie.replace(/;\s+/gim,"\",\"").replace(/=/gim, "\":\"") + "\"}")[key];    
        }     
        setInterval(function(){    
            console.log("name=" + getCookie("name"));    
        }, 10000);    
    });  
</script>  

postMessage

这个其实有点限制,就是你必须拿到目标窗口的引用,否则是通信不了的, 先看效果:


test4.gif

先用koa起2个服务(端口号设置不一样就行),分别放置2个index.html.

<!--http://localhost:3009/index.html-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
    <style>
        #div1 {
            width: 200px;
            height: 200px;
            background-color: red;
        }
    </style>
    <title>Document</title>
</head>
<body>
    <button id="button1">send</button>
    <button id="button2">get</button>
    <script>
        const targetWindow = window.open('http://localhost:3008/index.html'); //这步很重要,你必须拿到这个引用才行
        jQuery('#button1').on('click', () => {
            let data = parseInt(Math.random() * 10);
            console.log(`发送数据${data}`);
            targetWindow.postMessage(data, "http://localhost:3008")
        })
        window.addEventListener('message', function(e) {
            console.log(`接受到数据:${e.data}, 数据源:${e.origin}`)
        }, true)
    </script>
</body>
</html>
<!--http://localhost:3008/index.html-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
    <style>
        #div1 {
            width: 200px;
            height: 200px;
            background-color: red;
        }   
        body {
            background-color: grey;
        }
    </style>
    <title>Document</title>
</head>
<body>
    <button id="button1">send</button>
    <button id="button2">get</button>
    <script>
        window.addEventListener('message', function(e) {
            jQuery("body").append(`<p>${e.data}</p>`)
        }, false)
    </script>
</body>
</html>

参考文献

https://www.cnblogs.com/lovling/p/7440360.html
https://blog.csdn.net/u014465934/article/details/98869766

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值