您好我正在尝试根据其内容调整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>
请帮助我解决如何从其他域
答案 0 :(得分:0)
您可以使用相同的域来避免跨域安全保护,也可以使用 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)
}, "*");
}
}