两种同源浏览器tab页通信方式(即看即用)

263 阅读1分钟

使用Broadcast Channel。

实现效果:

实现步骤

  • 1,在bbb.html 生成BroadcastChannel 对象
  • 2,在bbb.html 广播所要发送的数据
  • 3,在ccc.html 生成与bbb.html同key的BroadcastChannel 对象
  • 4,在ccc.html 监听bbb.html广播出来的数据

bbb.html代码

<!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">
    <title>Document</title>
</head>

<body>
    <!-- <iframe width="0" height="0" src="http://localhost:3001/a.html"></iframe> -->
    <div id='click'>点击</div>
    <script>
        click.onclick = function (e) {
            /* BroadCast Channel 通信 */

            // 1,生成BroadcastChannel 对象
            const bc = new BroadcastChannel('BCC');
            // 2,发送数据
            bc.postMessage('我是BroadcastChannel通信方式的数据')

        }
    </script>
</body>

</html>

ccc.html代码

<!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">
    <title>Document</title>
</head>

<body>
    <div id='click'>接受</div>
    <script>
        // 监听BroadcastChannel发送的数据
        const bc = new BroadcastChannel('BCC');
        bc.onmessage = function (e) {
            console.log('receive:', e.data);
        };
    </script>
</body>

</html>

使用localstorage。

原理:设置localStorage时会出发一个storage事件,监听该事件可以获取当前存储的数据

实现效果:

实现步骤

  • 1,在bbb.html 向localstorage存储要发送的数据
  • 2,在ccc.html 监听storage事件获取bbb.html存储的数据

bbb.html代码

<!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">
    <title>Document</title>
</head>

<body>
    <!-- <iframe width="0" height="0" src="http://localhost:3001/a.html"></iframe> -->
    <div id='click'>点击</div>
    <script>
        click.onclick = function (e) {
            // 要发送的数据
            const data = '使用localStorage发送数据'
            // 将数据存入localStorage 此处加上时间戳因为如果存入相同的数据讲不回触发storage事件
            localStorage.setItem('info', data + new Date)
        }
    </script>
</body>

</html>

ccc.html代码

<!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">
    <title>Document</title>
</head>

<body>
    <div id='click'>接受</div>
    <script>
        // 监听storage事件,取出发送的数据 (比对key,确定是发送数据而不是存储数据)
        window.addEventListener('storage',function (e) {
          if(e.key === 'info') return console.log('receive:',e.newValue);
        })
    </script>
</body>

</html>

642