JS:window之间、iframe之间的JS通信

一、Window之间JS通信

在开发项目过程中,由于要引入第三方在线编辑器,所以需要另外一个窗口(window),而且要求打开的window要与原来的窗口进行js通信,那么如何实现呢?

1、在原窗口创建新打开window的一个对象:

var new_window;
var url = 'http:://second.com';
new_window = window.open(url, 'new_window');

新窗口里有一个say()方法:

function say() {
      alert('hello, second!');            
}

2、使用对象调用新窗口里的say()方法:

new_window.say();

那么,如何在新窗口中调用原来窗口的方法呢???假设在原窗口有一个hello()方法:

function hello() {
    alert('hello, The first!');
}

新窗口可以使用window.opener调用原窗口的方法哦!如下所示:

window.opener.hello();

 

二、iframe之间JS通信

<script type="text/javascript">
    function hello()
    {
        console.log('拾空网say hello!');
        return '拾空网say hello!';
    }

    function callChildren()
    {
        var state = window.frames["children"].document.readyState;
        if (state == 'complete') {
            children.window.say(); // 调用子页面里面的js方法
            //parent.window.hello(); // 调用父页面方法
        }
    }
</script>
<div style="border:1px solid #F00">
 <h3>test iframe connection</h3>
 <input type='text' name="sex" value="male"/>
 <input type="button" name="test_js" value="测试js调用" onClick="javascript:callChildren()"  />
 <iframe name="children" src="host/" width="100%" height="100%" scrolling="yes" frameborder="1"></iframe>
</div>

 

posted @ 2016-08-01 20:08  冰狼爱魔  阅读(1082)  评论(0编辑  收藏  举报