您好,我正在尝试根据其内容调整 iframe 的大小,但它不起作用可能是因为跨域
这是我使用的代码
<script language="javascript" type="text/javascript">
function resizeIframe(obj) {
obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
}
</script>
<iframe src="http://other_domain_name/get?v=07armilCx5A" frameborder="0" scrolling="no" id="iframe" width="100%" height="300px" onload="javascript:resizeIframe(this);"></iframe>
请帮助我如何解决这个问题以从其他域获取 iframe 中的页面
最佳答案
您可以使用相同的域来避免跨域 安全保护或使用postMessage。 这只有在您可以控制 iframe 内容时才有可能...
您可能需要根据您的上下文(iframe ID 等)调整此代码,但它为您提供了一个可行的解决方案:我在 homair.com 上使用它。当我在我的电脑上开发时,我遇到了跨域问题,这让我可以避免这种情况 ;)
别怕,仔细研究代码还是很简单的!!
在父网站端:
function adjustIframe(height) {
if (!height) {
try {
height = jQuery("#your-iframe").contents().height();
}
catch (e) {
}
}
jQuery("#iframe-wrapper").height(height);
}
function listenIframe() {
// Here "addEventListener" is for standards-compliant web browsers and "attachEvent" is for IE Browsers.
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
// Now...
// if "attachEvent", then we need to select "onmessage" as the event.
// if "addEventListener", then we need to select "message" as the event
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
// Listen to message from child IFrame window
eventer(messageEvent, function (e) {
if (e.origin == 'http://your_iframe_domain.com') {
// Action asked from the JS in the iframe
if (e.data.action == 'resizeWindow') {
adjustIframe(e.data.height);
}
}
}, false);
}
在 iframe 内容端:
function adjustParentIframe() {
// try to call the parent JS function, if the domain is the same
try {
setTimeout(parent.adjustIframe, 500);
}
// if not => exception catched
catch (ex) {
// Using window.parent.postMessage("data", targetOrigin);
// Send a message to the parent window,
// which listen to the events, coming from the iframe.
window.parent.postMessage({
// action to do on the parent side.
action: 'resizeWindow',
// Arguments to send : the height of this page (the iframe content !)
height: ($(document).height() + 10)
}, "*");
}
}
关于javascript - iframe 调整高度自动不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27360275/