[英]iframe resize height automatically not working
Hello i am trying to resize the iframe based on its content but its not working may be becuase of the cross domain 您好,我正在尝试根据其内容调整iframe的大小,但无法正常工作可能是由于跨域
here is the code i am using 这是我正在使用的代码
<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>
Please help me how this will be resolved to grab a page in iframe from other domain 请帮助我解决该问题以从其他域中的iframe中抓取页面
you can either use the same domains to avoid cross-domain security protection OR use postMessage . 您可以使用相同的域来避免跨域安全保护,也可以使用postMessage 。 This is possible only if you have control of the iframe content... 只有在您可以控制iframe内容的情况下,才有可能...
You'll probably need to adapt this code to your context (iframe ID, etc), but it gives you a working solution : I'm using it on homair.com. 您可能需要将此代码修改为适合您的上下文(iframe ID等),但它为您提供了一个可行的解决方案:我在homair.com上使用它。 When I'm developing on my computer, I've the crossdomain problem, this allows me to avoid this ;) 当我在计算机上进行开发时,遇到了跨域问题,这使我可以避免这种情况;)
Don't be afraid, it's quite simple if you study the code in detail !! 不用担心,如果您详细研究代码,这很简单!
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);
}
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)
}, "*");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.