iframe数据传递汇总

2,113 阅读1分钟

iframe是在一个页面中嵌入另一个业务或者功能最快的方式,那么父容器向子容器以及子容器向父容器数据传递就是父容器和子容器信息传递的桥梁了。


  • 通过postMessage 父容器获取到iframe的容器,然后,通过postMessage传递给子容器数据,子容器监听message方法,父容器触发message的时候就可以拿到数据。
// 父容器
<iframe id="childIframe" title="childIframe" width="600" height="400" src="./child/index.html">
<script>
    const iframeWrap = document.querySelector('#childIframe');
    const parentData = {
        name: '父容器传递给子容器的数据'
    }
    iframeWrap.contentWindow.postMessage(parentData, '*')
</script>
// 子容器
<script>
    window.addEventListener('message', function (e) {
        console.log(e.data);
    })
</script>
  • 通过url 在嵌入iframe的时候,在参数中拼接参数,可以在子容器中截取
// 父容器
<iframe id="childIframe" title="childIframe" width="600" height="400" src="./child/index.html?a=1&b=2">
// 子容器
<script>
    var queryStr = window.location.hash.split("?")[1];
    var queryArr = queryStr.split("&");
    var queryObj = {};
    for (let i = 0; i < queryArr.length; i++) {
        var pairs = queryArr[i].split("=");
        queryObj[pairs[0]] = pairs[1];
    }
</script>

如果符合同源的子容器,也可以通过sessionStorage或者window上直接挂载数据的方式进行父容器和子容器数据的传递。