您的当前位置:首页正文

frame之间传值的方法

来源:要发发知识网

1.messageAPI

poseMessage方法可以允许来自不同源的脚本采用异步方式进行有限的通信,可以实现跨文档,多窗口,跨域消息传递。
post(data,origin)

  • data 要传递的数据
  • origin 指明目标窗口的源,协议+主机+端口号[URL],URL可以忽略,设置源后只会传递给指定窗口,*为任意窗口,/为同源窗口
    主窗口:
<body>
    <iframe src="inner.html"></iframe>
    <button type="button" id="click">click</button>
    <script>
        (function(){
            
            window.frames[0].postMessage('red','*');    
            document.getElementById('click').addEventListener('click',function(){
                window.frames[0].postMessage('red','*');
            });

        })();
    </script>
</body>

子窗口:

<body>
    <div id="red">hello world</div>
    <script>
        (function(){

            window.addEventListener('message',function(event){
                //检查发送消息的窗口是否为父窗口
                if(event.source!==window.parent){
                    return;
                }

                var red=document.getElementById('red');
                red.innerText=event.data;
            });
        })();
    </script>
</body>