• iframe操作(跨域解决等)


    note:当页面内嵌入一个iframe实际上是在dom上新建了一个新的完整的window对象

    iframe中取得主窗体

    window.top (顶级窗口的window对象)

    window.parent (当前iframe的父窗体window) 

    多层嵌套的iframe window.parent.parent....来取

    取得需要的window后可进行操作父文档的内容

    如: window.top.document.getElementById(''xxx");

    主窗体中取得iframe所属的window对象

    window.frames['iframe的名字']    (通过iframe上的name属性)

    document.getElementById("HtmlEdit").contentWindow;  (通过原生的方式,所有主要浏览器都支持 contentWindow 属性)

    示例:

    <iframe  ID="HtmlEdit" MARGINHEIGHT="1" MARGINWIDTH="1" width="100%" height="312">
    </iframe>

    参考: http://blog.csdn.net/dongzhiquan/article/details/5851201

    如(主窗口中操作iframe刷新):

    document.getElementById('FrameID').contentWindow.location.reload(true);

    也可以直接jquery操作attr刷新: $('#frameID').attr('src','http://xxx');

    浏览器同源策略:1.不能通过ajax的方法去请求不同源中的文档 2.浏览器中不同域的框架之间是不能进行js的交互操作的

    如果iframe涉及到跨域,这时进行iframe window对象的操作会访问受限

    chrome提示:

    Uncaught SecurityError: Blocked a frame with origin "http://123.57.6.131" from accessing a frame with origin "http://localhost:9000". Protocols, domains, and ports must match.

    firefox提示:

    Permission denied to access property "xxx"

    这里有两种情况,

    1.子级域名之间跨域

    2.完全不同域名跨域

    1.子级域名之间跨域操作,指定相同的document.domain即可

    如:

    http://www.example.com/a.html 和  http://example.com/b.html
    这两个页面的document.domain都设成相同的域名就可以了  example.com
    只能把document.domain设置成自身或更高一级的父域,且主域必须相同,然后即可无阻访问,进行相应操作

    2.完全不同域的情况,传值 (通过iframe所属的window对象的location.hash传值)

    2.1 主窗体传值给iframe

    由于操作location.hash不会造成整个iframe的重载刷新,所以可以这样操作,然后在iframe中监听onhashchange事件

    如:

    //主窗体中传递json数据到iframe:
    var url;
    var data = {name:'xx',age:26};
    var tmp = encodeURI( JSON.stringify(center) );
    $('#iframe_id').attr('src',url+'#'+tmp);
    
    //iframe中接收 
    window.onhashchange = function () {
        var hash_str = decodeURI( window.location.hash.replace('#','').toString() );
        var data = JSON.parse( hash_str ); 
    }
    
    // 这样一旦当url hash值改变,iframe就可以进行相应调整
    // 如果要兼容ie8之类不支持onhashchange事件的浏览器
    // 可以用setInterval()判断是否发生改变,然后调用相应函数

    参考: http://stackoverflow.com/questions/3090478/jquery-hashchange-event

    2.2 iframe中传递给主窗体

    需要在主窗体a同域名下新建一个页面c

    然后在iframe b中嵌入iframe src值为页面c,

    iframe b中便可用同样的方式操作c的url hash值,

    a,c同域名下即可透明访问操作, a访问c的window对象不存在跨域同源限制的问题.

    3.父window 操作子iframe中的dom元素,通过子iframe的window的document对象操作

    如:
    var dd = $(window.frames['frame_name'].document).contents.find('a');
    dd.attr('target','_self');


    注意有必要放到iframe加载完成后再操作

    $('#xx_content > iframe').load(function () {
        ...
    });
  • 相关阅读:
    php之static静态变量详解
    设计模式【代理模式】
    小牟Andorid下面MD5具体实现的思路总结
    ubuntu14.04安装MySQL
    Android手机定位技术的发展
    我不同意你,这是您的支持
    我要遵守11文章数据库设计指南
    quick-cocos2d-x游戏开发【3】——display.newSprite创建向导
    第二章 自己的框架WMTS服务,下载数据集成的文章1
    JSTL实现int数据的类型的长度
  • 原文地址:https://www.cnblogs.com/isdom/p/webclips046.html
Copyright © 2020-2023  润新知