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

1,990 阅读1分钟

使用iframe实现

实现效果

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 src="http://localhost:3001/a.html"></iframe>
    <div id='click'>点击</div>
    <script>
        click.onclick = function () {
            // 向iframe发送数据,iframe端口3001,与当前bbb.html不同源。但是发送数据给iframe
            window.frames[0].window.postMessage('使用iframe作为中介发送数据', '*')
        }
    </script>
</body>

</html>

iframe页面

<!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>
    a.html
    <script>
        window.addEventListener('message', function (e) {
            // 接受非同源父页面(http://localhost:3000/bbb.html)发送的数据,
            // 使用BroadcastChannel进行广播数据( b.html 与当前iframe同源 同属于3001端口 ,所以 b.html可以接收到广播出去的数据)
            const data = e.data
            // 通过BroadCast Channel 向当前同源页面通信
            const bc = new BroadcastChannel('iframe_connect');
            bc.postMessage(e.data)
        })
    </script>
</body>

</html>

b页面

<!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>
    b.html
    <!-- <iframe width="0" height="0" src="http://localhost:3001/c.html"></iframe> -->
    <script>
        const bc = new BroadcastChannel('iframe_connect')
        bc.onmessage = function (e) {
            // 接受iframe广播出来的数据并打印
            console.log('receive:',e.data);
        }
    </script>
</body>
</html>

508