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

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

作者: ChenReal | 来源:发表于2024-05-15 19:05 被阅读0次

背景

我们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来传递参数。总的来说,该方案应该属于远古时代的产物,如果不考虑兼容旧的浏览器,不推荐大家在项目上使用。可以把它放到代码的博物馆中,慢慢欣赏,就好比今天我们像看古人如何钻木取火一般。

相关文章

  • 什么是跨域?跨域有几种实现形式:

    跨域指的是跨过同源策略,实现不同域之间进行数据交互的过程叫跨域。跨域的实现形式主要有JSONP方法、CORS方法、...

  • 跨域

    跨域指的是跨过同源策略,实现不同域之间进行数据交互的过程叫跨域。跨域的实现形式主要有JSONP方法、CORS方法、...

  • 前端跨域

    前端做网络轻取i存在跨域问题,准确的说是Ajax实现的数据交互,因为表单不存在跨域问题的哈。现目前主要的解决方法主...

  • [mark]九种跨域方式实现原理

    前端如何使用proxyTable和nginx解决跨域问题 前言 前后端数据交互经常会碰到请求跨域,什么是跨域,以及...

  • vueJS使用leadcloud数据存储

    vue前端使用leadcloud数据存储,实现纯前端+leadcloud进行数据交互,无需server端,轻松实现...

  • webpack4基本使用(四)-跨域-环境变量

    16 wepack跨域问题 通过前端代理实现跨域 如果前端只是模拟数据时,我们可以使用devServer 自带的e...

  • Javascript跨域整理

    在前端的JS请求中,跨域的问题经常存在,根据不同的实现原理,常见的跨域的方法如下: 一:前端的方式 1:在前端页面...

  • 前端跨域

    什么是跨域? 协议、域名、端口有一处不一样,都是不同的域,两个不同域的信息交互就是跨域。 跨域的具体实现 单向跨域...

  • 史上最全前端开发跨域解决方案整理!必须收藏!

    在我们做项目开发的时候,前端做数据交互,尤其是做数据获取的时候,经常都会遇到跨域的问题,那到底什么是跨域问题呢?今...

  • vue-cli proxyTable配置

    前端的跨域转发 后端不需要配置,前端就可以实现跨域 proxyTable 的通常配置 这样就可以实现基本的跨域转发...

网友评论

      本文标题:纯前端实现网页跨域交互数据的两个方法

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