父页面获取子页面的window对象
/** * 在父页面获取iframe的window对象 * chrome:iframeElement. contentWindow * firefox: iframeElement.contentWindow * ie6:iframeElement.contentWindow */function getIframeWindow(iframeElement) { return iframeElement.contentWindow; // return iframeElement.contentWindow || iframeElement.contentDocument.parentWindow;}
父页面获取子页面的document对象
/** * 在父页面获取iframe的document * chrome:iframeElement.contentDocument * firefox:iframeElement.contentDocument * ie:element.contentWindow.document * 备注:ie没有iframeElement.contentDocument属性。 */function getIframeDocument(element) { console.dir(element); return element.contentDocument || element.contentWindow.document;};
iframe何时装载完毕
/** * 下面的代码能正常运行于所有的浏览器之上。 * 由于iframe元素包含于父级页面中,因此以上方法均不存在跨域问题。 * 实际上IE提供了onload事件,但必须使用attachEvent进行绑定。 */function iframeOnload() { var iframe = document.createElement("iframe"); iframe.src = "simpleinner.htm"; if (iframe.attachEvent) { iframe.attachEvent("onload", function () { alert("Local iframe is now loaded."); }); } else { iframe.onload = function () { alert("Local iframe is now loaded."); }; } document.body.appendChild(iframe);}
利用onload和attachEvent,实现iframe高度自适应
/** * 如果iframe的高度不足屏幕可视区域的高度,则iframe的高度 === 屏幕可视区域的高度 * 如果iframe的高度大于屏幕可视区域的高度,则iframe的高度 === iframe自己的高度 * */ function setFrameHeight(iframe) { var iframeDoc = iframe.contentDocument || iframe.contentWindow.document; var offsetHeight = iframeDoc.childNodes[1].offsetHeight; var clientHeight = document.documentElement.clientHeight||document.body.clientHeight; iframe.height = offsetHeight > (clientHeight-35) ? offsetHeight : (clientHeight-35); } function iframeOnload() { var iframe = document.getElementById("iframe"); if (iframe.attachEvent) { iframe.attachEvent("onload", function () { setFrameHeight(this); }); } else { iframe.onload = function () { setFrameHeight(this); }; } }
在子页面中获取父页面的window对象
/** * 存在跨域问题 * 在子页面中获取父页面的window对象 * 父页面:window.parent * 适用于所有浏览器 */console.log(window.parent);
在子页面中获取顶层页面
/** * 存在跨域问题 * 在子页面中获取顶层页面 * 顶层页面:window.top * 适用于所有浏览器 */console.log(window.top);
在子页面中获取iframe的html
/** * 存在跨域问题 * 在子页面中获取iframe的html * window.frameElement * (类型:HTMLElement) * 适用于所有浏览器 */console.log(window.frameElement);
BUG##Blocked a frame with origin "null" from accessing a cross-origin frame.
跨页面操作涉及域的概念(origin),错误的意思是:未捕获的安全错误:阻止了一个域为null的frame页面访问另一个域为null的页面。代码运行时在本地直接用浏览器打开的,地址栏是file:///的页面,只需改为localhost访问就行。