Resize iframe and its parent height according to c

2020-05-06 12:04发布

问题:

There are many questions answered regarding resizing iframe height according to it's content, but what if the content gets too lengthy and exceeds the height of the container. In this case I want the container height to resize accordingly and without iframe getting scrolls or trimmed in case of setting overflow to hidden. How can I do this?

回答1:

Since your document and iframe are different domains, the javascript from one cannot directly access the DOM of the other (see same-origin security restrictions). That means that you cannot directly reach into the DOM of the iframe to find out how large it would like to be such that you can set the iframe size to that size from within the containing document.

Any options you have for doing this require some code control within the iframe. For example, you could support window.postMessage() between the two iframes and the containing document could ask the iframe how large it would like to be via window.postMessage() and when it receives the response, it could then change the iframe size.

Various references:

cross-domain iframe resizer?

http://css-tricks.com/cross-domain-iframe-resizing/

Cross-domain, cross-browser Iframe communcation, made easy!

Yet Another cross-domain iframe resize Q&A

https://github.com/davidjbradshaw/iframe-resizer