html,获取iframe的window,document,自定事件与iframe通信

 
获取iframe的window对象js代码如下.注意:一定要在文档加载完成之后,才能获取到
var Iframe=document.getElementById("script");//先获取到iframe元素
var iframeWindow=(Iframe.contentWindow || Iframe.contentDocument);//获取到指定iframe下window

对应html代码:

<iframe  class="Panel" id="script" src="t.html"></iframe>

以上代码就能实现获得页面中iframe的window对象

现在实现iframe和父页面通信,

page1(为iframe页面代码):

<!DOCTYPE html>
<html>
<head>
    <meta charset=utf-8" />
    <title>By:DragonDean</title>
    <script src="jquery.js"></script>
    <script type="application/javascript">
       window.onload=function(){
            window.evt=document.createEvent('Event');//创建一个事件,挂在当前页面的window对象上
            window.evt.initEvent('myEvent',true,true);//初始这个事件
            var obj=document.getElementById('testBtn');
            obj.addEventListener('click', function(){//自定义事件触发的条件,例子中用的点击
                window.evt.test='测试iframe之间用事件传数据';//测试传值
                window.dispatchEvent(window.evt);//让自定义事件触发
            }, false);
    console.log(parent);//父页面的window对象,iframe嵌入页面自带
    };
  
</script></head> <body> <button id="testBtn">test</button> </body> </html>

page2(主页面):

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script>
     window.onload=function(){
         var Iframe=document.getElementById("script");//先获取到iframe元素
         var iframeWindow=(Iframe.contentWindow || Iframe.contentDocument);//获取到指定iframe下window
         /*在主页面对iframe页面的window上添加一个监听事件,监听自定义事件,传入一个当前页面的函数,获取iframe触发的事件*/
         iframeWindow.addEventListener('myEvent',function(event){//event为t.html中触发这个监听的window.evt事件
             console.log(event.test);//到此,传值完成
         })
     }
    </script>
</head>
<body>
<iframe  class="Panel" id="script" style="height: 1000px;" src="page1.html" name="script"></iframe>
</body>
</html>

将两个页面放同目录下,运行page2,呼出控制台,就能看到传值结果。

原文地址:https://www.cnblogs.com/v-weiwang/p/4915098.html