纯前端实现网页跨域交互数据的两个方法

背景

我们Web前端开发者一般都会有这样的常识:同一浏览器打开了两个不同域名的网页,两个页面之间被沙箱隔了,因此是无法进行数据交互的。这两个页面一旦尝试用JS相互访问资源,便会报错。

除非,你是借助服务端的能力(例如:AJAX或者WebSocket之类),间接地进行通讯。

浏览器限制站点跨域访问是出于保护客户端信息安全需要,这一点无可厚非。但我们Web前端的某些开发场景,确实有需求跨域做交互,怎么办呢?

下面分享一下我的做法。

PS. 因为今天我想讨论的是纯前端的技术解决方案,依赖服务端解决办法忽略掉。Ajax 和 WebSocket,你们都要出局啦!

两种跨域场景

Web跨域的场景通常有两种:

  • 1.iframe的内嵌页面与主窗口页面之间的通讯
  • 2.通过window.open打开新窗口与母窗口(opener)之间的通讯

我下面的案例会分别针对这两种场景提供对应的方案。

方案1:使用window.postMessage的API

window.postMessage 是 html5 引入的新API,它允许来自不同源的脚本采用异步方式进行有效的通信,可以实现跨文本文档、多窗口、跨域消息传递,多用于窗口间数据通信。

从上面的介绍可以看出来,这算是w3c标准的跨域通信的解决方案。

首先我们模拟一个跨域场景:假设我有两个网页,访问地址分别为

1、处理iframe跨域的代码示例

  • A页面代码:
<html>
    <head>
        <title>Example CORS for iframe</title>
    </head>
    <body>
        <button>Post Message</button>
        <p></p>
        <iframe src="http://b.example.com/test.html" width="500" height="300"></iframe>
    </body>
    <script>
        const iframe = document.querySelector('iframe');
        const button = document.querySelector('button');
        const msg = document.querySelector('p');
        button.addEventListener('click', () => {
            iframe.contentWindow.postMessage('hello', '*');
        });

        window.addEventListener('message', (event) => {
            msg.innerText = `Message from iframe: ${event.data}`;
        });

    </script>
</html>
  • B页面代码:
<html>
    <head>
        <title>Inner Page</title>
    </head>
<body>
    <h1>Hi, this is an inner page</h1>
    <p></p>
    <div></div>
</body>
</html>
<script>

window.onload = ()=>{

    setInterval(()=>{
        var time = new Date().getTime().toString();
        document.querySelector('p').innerHTML = `Current Timestamp:${time}`;
        
        window.parent.postMessage(time,'*');    
    },1000);

    window.addEventListener('message',(e)=>{    
        document.querySelector('div').innerHTML = `Message from Parent:${e.data}`;  
    });
}
</script>

2、处理弹窗的跨域的代码示例

  • A页面代码:
<html>
    <head>
        <title>Example CORS for window.open</title>
    </head>
    <body>
        <button>Post Message</button>
        <p></p>
    </body>
    <script>
        var childWindow;
        function openWindow(url, width, height) {
            var h = screen.height * height / 100;
            var w = screen.width * width / 100;
            var x = (screen.width - w) / 2;
            var y = (screen.height - h) / 2;

            return window.open(url, '_blank', 'width=' + w + ',height=' + h + ',top=' + y + ',left=' + x);
        }

        window.onload = function() {
            childWindow = openWindow('http://b.example.com/test.html', 40, 30);
        };

        const button = document.querySelector('button');
        const msg = document.querySelector('p');
        button.addEventListener('click', () => {
            childWindow.postMessage('hello', '*');
        });

        window.addEventListener('message', (event) => {
            msg.innerText = `Message from iframe: ${event.data}`;
        });

    </script>
</html>
测试结果
  • B页面代码:
<html>
    <head>
        <title>Inner Page</title>
    </head>
    <body>
        <h1>Hi, this is an inner page</h1>
        <p></p>
        <div></div>
    </body>
</html>
<script>
    window.onload = ()=>{
        setInterval(()=>{
            var time = new Date().getTime().toString();
            document.querySelector('p').innerHTML = `Current Timestamp:${time}`;
            window.opener.postMessage(time,'*');
        },1000);

        window.addEventListener('message',(e)=>{            
            document.querySelector('div').innerHTML = `Message from Parent:${e.data}`;
        })
    }    
</script>
测试结果

方案2:利用window.name传递信息

处理iframe跨域的代码示例(一)

  • A页面代码:
<html>
    <head>
        <title>Example CORS for iframe</title>
    </head>
    <body>
        <button>Post Message</button>
        <p></p>
        <iframe src="http://b.example.com/test.html" width="500" height="300"></iframe>
    </body>
    <script>
        const iframe = document.querySelector('iframe');
        const button = document.querySelector('button');
        const msg = document.querySelector('p');
        button.addEventListener('click', () => {
            iframe.contentWindow.title = 'ToChild:hello';
        });

        setInterval(() => {
            var name = iframe.contentWindow.name;
            if(name && name.startsWith('ToParent:')) {
                msg.innerHTML = 'Message from iframe:'+name.substring(9);
            }
        }, 200);

    </script>
</html>
  • B页面代码:
<html>
    <head>
        <title>Inner Page</title>
    </head>
    <body>
        <h1>Hi, this is an inner page</h1>
        <p></p>
        <div></div>
    </body>
</html>
<script>
    window.onload = ()=>{
        setInterval(()=>{
            var name = window.name;
            if(name && name.startsWith('ToChild:')){
                var message = name.substring(8);
                document.querySelector('div').innerHTML = `Message from Parent:${message}`;
            }
            var time = new Date().getTime().toString();
            document.querySelector('p').innerHTML = `Current Timestamp:${time}`;
            window.name=`ToParent:${time}`;
        },1000);
    }    
</script>
  • 注意:不出意外的话就要出意外了……


    测试出现报错

以上报错证明:非常可惜,现代浏览器已经把这个口子给堵上了,这个方法仅适用于古代的浏览器。但是不要沮丧,既然我敢发出来,肯定还有别的招数。虽然不完太美,能够使用的范围有限,聊胜于无吧。

处理iframe跨域的代码示例(二)

这个方案我们需要增加一个跟页面A同域的空白页面作为跳板,例如:

  • http://a.example.com/empty.html
    empty.html页面完全为空,不包含任何代码也没关系。做好这一步后,我们来重写A、B两个页面的代码:

  • A页面代码:

<html>
    <head>
        <title>Example CORS for iframe</title>       
    </head>
    <body>
        <button>Post Message</button>
        <p></p>
    </body>
</html>

<script>
    const msg = document.querySelector('p');
    function openFrame(url, fn) {
        var iframe = document.createElement('iframe');
        iframe.style.display = 'none';
        var state = 0;
        var cb = fn;
        iframe.onload = function() {
            if(state === 1) {
                cb(iframe.contentWindow.name);
                iframe.contentWindow.document.write('');
                iframe.contentWindow.close();
                document.body.removeChild(iframe);
            } else if(state === 0) {
                state = 1;
                setTimeout(() => {
                    iframe.contentWindow.location = 'empty.html';
                },300)
            }
        };
        iframe.src = url;
        document.body.appendChild(iframe);
    }    
    setInterval(() => {
        var url = 'http://b.example.com/test.html';
        openFrame(url, (data)=> {
            message = data;
            if(data && data.startsWith('ToParent:')) {
                msg.innerHTML = 'Message from iframe:'+data.substring(9);
            }
        });  
    }, 1000);
</script>
  • B页面代码:
<script>
    var time = new Date().getTime().toString();
    window.name=`ToParent:${time}`;
</script>
测试成功

总结

  • 以上两种方法,便是纯前端实现的跨域通讯。
  • window.postMessage是浏览器的标准API,它实现的通讯非常实时,而且代码的实现方式也相当优雅,强烈推荐大家使用。当然,使用的时候要注意浏览器兼容性,兼容旧版的浏览器比如IE,那么可以考虑用另外一个方案。
  • 利用window.name也确实能够实现在iframe跨域通讯的目标,尽管代码看起来比较绕。不过,也确实是打了折扣,因为信息传递只能有单向的通道(A页面获取B页面的信息)。当然,如果想实现A=>B传递信息,也有其他手段,譬如利用URL来传递参数。总的来说,该方案应该属于远古时代的产物,如果不考虑兼容旧的浏览器,不推荐大家在项目上使用。可以把它放到代码的博物馆中,慢慢欣赏,就好比今天我们像看古人如何钻木取火一般。
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 前端开发中,跨域使我们经常遇到的一个问题,也是面试中经常被问到的一些问题,所以,这里,我们做个总结。小小问题,不足...
    Nealyang阅读 481评论 0 0
  • 1、JSONP 受浏览器同源策略的限制,网页无法向其他域发送ajax请求,但在页面中引入其他域的脚本是可以的,最常...
    cfighter阅读 523评论 0 1
  • 前端跨域问题 浏览器的同源策略 提到跨域不能不先说一下”同源策略”。何为同源?只有当协议、端口、和域名都相同的页面...
    单只蝴蝶_569d阅读 379评论 0 0
  • 什么是跨域 浏览器出于安全方面的考虑,只允许客户端与本域(同协议、同域名、同端口,三者缺一不可)下的接口交互。不同...
    七里之境阅读 1,369评论 0 0
  • 同源:协议、域名、端口相同 跨域通信: js进行DOM操作,通信时如果目标与当前窗口不满足同源条件,浏览器为了安全...
    silly鸿阅读 631评论 0 1