美文网首页
实现Tab页之间通信的方式

实现Tab页之间通信的方式

作者: 李牧敲代码 | 来源:发表于2020-04-23 16:34 被阅读0次

    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

    这个简单就不讲了

    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

    相关文章

      网友评论

          本文标题:实现Tab页之间通信的方式

          本文链接:https://www.haomeiwen.com/subject/brqwihtx.html