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 () { ... });
