I am trying to adjust the height of an iframe to its content. The iframe will be added dynamically by JavaScript, meaning JavaScript has to deal with the element's properties as well:
let iframe = document.createElement("iframe");
iframe.src = "https://en.wikipedia.org/";
document.getElementById("foo").appendChild(iframe);
iframe.onload = function() {
iframe.style.height = "600px";//<-- Does work, why?
resizeIframe(iframe);//<-- Does not work
//iframe.style.height = iframe.contentWindow.document.body.scrollHeight + "px"; //<-- Does not work (when uncommented)
}
function resizeIframe(obj) {
obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
}
<div id="foo">
<!-- Iframe to be inserted in here -->
</div>
Does anyone happen to know what I could do to make this work? I found the following solution and applied it to the code available above:
function resizeIframe(obj) {
obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
}
The JavaScript function might (although in this example it would not) work for a plain HTML generated <iframe>
, when it comes to a JavaScript generated <iframe>
, it does not seem to work. Am I doing something wrong or should I use any alternative method?
Edit: I am using ASP.Net MVC, my project contains the following code in the view:
MyView.cshtml:
<div class="my-class text-center">
<span>
For testing purpose only, this elements has been added. Functionality:
</span>
<br />
<button id="loadiframe" class="btn btn-lg btn-primary" data-toggle="modal" data-target=".bs-example-modal-lg">
Load iframe
</button>
</div>
When the button is clicked, it should insert/add an iframe element to the .modal-content
part of a Bootstrap Modal:
myscript.js:
function foobar() {
let iframe = document.createElement("iframe");
iframe.src = "/home";
$(".modal .modal-content").html(iframe);
iframe.onload = function () {
iframe.style.height = iframe.contentWindow.document.body.scrollHeight + 'px';
}
}
$(document).ready(function() {
$("button#loadiframe").on("click", function () {
foobar();
});
});
This does seem to add the <iframe>
, but not adjust the height. Would anyone happen to know how I could fix this problem? This would be all happening on the same domain as I am referring to the "home" controller which can be found within my project and which is assigned to my <iframe>
source attribute (see code above).