zoukankan      html  css  js  c++  java
  • 同域下跨文档通信iframe和window.open

    1、iframe标签可以嵌套另一个标签,并且可以通过js去访问被包含的页面的window对象,从而操作该页面下documentElement,如下:

    <!DOCTYPE HTML>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>无标题文档</title>
    <script>
    
    window.onload = function() {
        
        var oBtn = document.getElementById('btn');
        var oMyIframe = document.getElementById('myframe');
        
        oBtn.onclick = function() {
            
            //如果我们要操作一个iframe里面的dom元素,首先要获取到iframe引入的页面的window
            //oMyIframe.contentWindow -> 被iframe包含的页面的window对象
            //alert(oMyIframe.contentWindow);
            
            oMyIframe.contentWindow.document.body.style.background = 'red';
            
        }
        
    }
    </script>
    </head>
    
    <body>
        <input type="button" value="点击我,改变2.iframe.html的背景色" id="btn" />
        <iframe id="myframe" src="2.iframe.html"></iframe>
    </body>
    </html>

    通过contentWindow来找到被包含页面的window对象,从而继续其他操作。那么被包含页面怎么找到他的父级页面呢?

    一个页面可以通过iframe来嵌套另外一个页面,被包含的页面又可以继续通过iframe标签也继续嵌套其他页面,这样就是一种层级关系

    我们知道window指的是当前页面窗口,那么parent指的是父级窗口,top指的是顶级窗口,三者可能会表示相同窗口。例如:

    parent.document.body.style.background = 'green';

    top.document.body.style.background = 'green';

    2、window.open

    通过window.open方法可以打开一个新窗口,并且返回的是被打开窗口的window对象。

    例如:

    newWindow = window.open('4.window.open.html', '_blank');

    相反,window.opener可以访问到通过window.open方法打开当前页面的窗口window,例如:

    window.opener.document.body.style.background = 'green';

    注意:iframe和window.open都只能解决同域下的跨文档通信!如果跨域,那么只能访问到window对象,window对象下的属性和方法豆浆禁止访问。

  • 相关阅读:
    airtest-selenium
    window下使用Redis Cluster部署Redis集群
    调用webservice进行身份验证
    ETL数据从sqlserver到mysql之间迁移
    Sqlserver调用api
    EXCEL导入数据到SQLSERVER
    博客园开通的第一天
    Visual Studio 2017 离线安装包
    WPF学习笔记1---初接触
    Visual Studio 2008 + ObjectARX2012环境配置
  • 原文地址:https://www.cnblogs.com/toodeep/p/4768171.html
Copyright © 2011-2022 走看看