1. ⭐️ 服务器中转(代理服务器)

    const http = require('http');
    const url = require('url');

    // 创建代理服务器
    const proxyServer = http.createServer((req, res) => {
        // 解析目标服务器的 URL
        const targetUrl = '<http://target-domain.com>' + req.url;
        const options = {
            hostname: url.parse(targetUrl).hostname,
            port: 80,
            path: url.parse(targetUrl).path,
            method: req.method,
            headers: req.headers
        };

        // 向目标服务器发送请求
        const proxyReq = http.request(options, (proxyRes) => {
            // 将目标服务器的响应返回给客户端
            res.writeHead(proxyRes.statusCode, proxyRes.headers);
            proxyRes.pipe(res);
        });

        req.pipe(proxyReq);
    });

    proxyServer.listen(3000);

2. ⭐️ document.domain + iframe

3. ⭐️ window.name + iframe

4. ⭐️ postMessage + iframe

页面 a 和页面 b 相互发消息的示例:

页面 a(父页面)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Page A</title>
</head>
<body>
    <h1>Page A</h1>
    <button id="sendToB">Send Message to B</button>
    <iframe id="iframeB" src="<http://example.com/b.html>" width="600" height="400"></iframe>

    <script>
        const iframe = document.getElementById('iframeB');

        // 发送消息给 B 页
        document.getElementById('sendToB').addEventListener('click', function() {
            const message = { text: "Hello from A!" };
            iframe.contentWindow.postMessage(message, '<http://example.com>'); // 目标源应为 B 页的真实 URL
        });

        // 接收来自 B 页的消息
        window.addEventListener('message', function(event) {
            // 验证消息来源
            if (event.origin !== '<http://example.com>') return; // 目标源应为 B 页的真实 URL

            // 处理消息
            console.log('Message from B:', event.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">
    <title>Page B</title>
</head>
<body>
    <h1>Page B</h1>
    <button id="sendToA">Send Message to A</button>

    <script>
        // 发送消息给 A 页
        document.getElementById('sendToA').addEventListener('click', function() {
            const message = { text: "Hello from B!" };
            window.parent.postMessage(message, '<http://parent.example.com>'); // 目标源应为 A 页的真实 URL
        });

        // 接收来自 A 页的消息
        window.addEventListener('message', function(event) {
            // 验证消息来源
            if (event.origin !== '<http://parent.example.com>') return; // 目标源应为 A 页的真实 URL

            // 处理消息
            console.log('Message from A:', event.data);
        });
    </script>
</body>
</html>

说明