iframe跨域-Js通信的一种方式

向外通知:

iframe外监听:
window.addEventListener('message',function(e){
        var data = e.data;
        console.log(data.info);//some info
        console.log(data.action);//dosomething

        var height = data.height;
        if(height < 250){
            height = 250;
        }
        var ifr = document.getElementById('iframeName').style.height = height + 'px';
    });
iframe内发消息:
window.parent.postMessage({height:$(document).height()}, '*');
window.parent.postMessage({action: 'dosomething', info: 'some info'},"*");

 

向内通知:

iframe内监听:
window.addEventListener("message", function(e){
    var data = e.data;
    console.log(data.info);//some info
    console.log(data.action);//dosomething
});
iframe外发消息:
document.getElementById('iframeName').contentWindow.postMessage({action: 'dosomething', info: 'some info'},"*");

  

(0)

相关推荐