This innovative approach was instrumental in seamlessly integrating a WordPress page into a Magento2 Page using an iframe. This was crucial for me as I required the WP template, and to my delight, it worked flawlessly.
The following JavaScript code was added:
// Custom function for getting document height
function getDocHeight(doc) {
doc = doc || document;
var body = doc.body, html = doc.documentElement;
var height = Math.max( body.scrollHeight, body.offsetHeight,
html.clientHeight, html.scrollHeight, html.offsetHeight );
return height;
}
// Function to set iframe height dynamically
function setIframeHeight(id) {
const ifrm = document.getElementById(id);
const doc = ifrm.contentDocument? ifrm.contentDocument: ifrm.contentWindow.document;
ifrm.style.height = getDocHeight( doc ) + 2 + "px";
}
Here is how the iframe code looks like:
<iframe id='wp-twoblock-0'
src='https://www.example.com/wp/twoblock'
onload='setIframeHeight(this.id);'
style='border:0px;vertical-align:bottom;width:100%;overflow:hidden;'
target='_PARENT' marginwidth='0'
marginheight='0' frameborder='0' scrolling='no' ></iframe>
The process functions as follows:
- The iframe content is loaded
- setIframeHeight function is triggered
- This adjusts the iframe height based on the content with the provided CSS, resulting in a seamless display without hidden content or double scrollbars!
You can view a demonstration of this implementation here:
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="">
<meta name="viewport" content="width=, initial-scale=">
<title></title>
<script>
function getDocHeight(doc) {
doc = doc || document;
var body = doc.body,
html = doc.documentElement;
var height = Math.max(body.scrollHeight, body.offsetHeight,
html.clientHeight, html.scrollHeight, html.offsetHeight);
return height;
}
function setIframeHeight(id) {
const ifrm = document.getElementById(id);
const doc = ifrm.contentDocument ? ifrm.contentDocument : ifrm.contentWindow.document;
ifrm.style.height = getDocHeight(doc) + 2 + "px";
}
</script>
</head>
<body>
<h1>Parent</h1>
<iframe id='wp-twoblock-0' src='otherdocument.html' onload='setIframeHeight(this.id);' style='border:0px;vertical-align:bottom;width:100%;overflow:hidden;' target='_PARENT' marginwidth='0' marginheight='0' frameborder='0' scrolling='no'></iframe>
</body>
</html>