/** * 在父页面获取iframe的window对象 * chrome:iframeElement. contentWindow * firefox: iframeElement.contentWindow * ie6:iframeElement.contentWindow */ function getIframeWindow(iframeElement) { return iframeElement.contentWindow; // return iframeElement.contentWindow || iframeElement.contentDocument.parentWindow; }
/** * 在父页面获取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元素包含于父级页面中,所以以上方法均不存在跨域问题。 * 实际上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); }
/** * 若是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.parent * 适用于全部浏览器 */ console.log(window.parent);
/** * 存在跨域问题 * 在子页面中获取顶层页面 * 顶层页面:window.top * 适用于全部浏览器 */ console.log(window.top);
/** * 存在跨域问题 * 在子页面中获取iframe的html * window.frameElement * (类型:HTMLElement) * 适用于全部浏览器 */ console.log(window.frameElement);
parent.window.parentMethod();
FrameName.window.childMethod();
跨页面操做涉及域的概念(origin),错误的意思是:未捕获的安全错误:阻止了一个域为null的frame页面访问另外一个域为null的页面。代码运行时在本地直接用浏览器打开的,地址栏是file:///的页面,只需改成localhost访问就行。html