Change Iframe Size Automatically To Fit Content & Prevent Scrollbars
Có thể bạn quan tâm
There are 2 ways to automatically change the size of an <iframe> so as to fit its content and prevent scrollbars :
- For same-domain iframes : From the parent page, the complete height & width of the iframe can be found through its contentDocument.body.scrollHeight & contentDocument.body.scrollWidth properties. These values can then be set as the CSS height & width of the <iframe> element.
- For cross-domain iframes : The iframe page can send a message to the parent page using postMessage(), informing about its size. On receiving the message, the parent page can change CSS height & width of the <iframe> element.
Same-Domain Iframes
For same-domain iframes, code changes are required only in the parent page. The iframe page needs no code changes.
- First we need to wait for the iframe to be loaded so that its correct dimensions are available.
- After iframe has been loaded, contentDocument.body.scrollHeight property gets its full height.
- contentDocument.body.scrollWidth property gets its full width.
Cross-Domain Iframes
For cross-domain iframes, code changes are needed in both the iframe & the parent page.
The iframe page needs to be loaded first to get correct dimensions. After loading, its dimensions are passed to the parent page using postMessage().
window.addEventListener('load', function() { let message = { height: document.body.scrollHeight, width: document.body.scrollWidth }; // window.top refers to parent window window.top.postMessage(message, "*"); });In the parent page, the message is recieved, and the <iframe> CSS dimensions are updated.
<iframe src="https://cross-domain.com/child.html" id="child-iframe"></iframe> <script> let iframe = document.querySelector("#child-iframe"); window.addEventListener('message', function(e) { // message that was passed from iframe page let message = e.data; iframe.style.height = message.height + 'px'; iframe.style.width = message.width + 'px'; } , false); </script>
Từ khóa » Html Iframe Resize To Fit Content
-
Make Iframe Automatically Adjust Height According To The Contents ...
-
How To Adjust The Width And Height Of Iframe To Fit With Content In It
-
Resize Iframe To Fit Content (Same Domain Only) - CSS-Tricks
-
Automatically Adjust IFrame Height According To Its Contents Using ...
-
How To Scale The Content Of
-
How To Fit Content In Iframe Code Example
-
Iframe Height 100 Code Example
-
How To Adjust Width And Height Of Iframe To Fit With Content In It
-
Resize External Website Content To Fit Iframe Width
-
How Do I Fit An Iframe To Its Size? - Brain Writings
-
Iframe Auto Adjust Height As Content Changes
-
Resize An Iframe To Fit Its Content - HTML DOM
-
Resize Iframe Height To Fit Content (works Cross Domain) · GitHub
-
Html – Resize Iframe Until There Is No Scrollbar(fit Content) - ITecNote