I have an iframe with the sandbox attribute. The content of this iframe is set directly through the 'srcdoc' attribute. The content is insecure as it can be set by users.
I want to adjust the height of the iframe to match the height of the content.
var my_iframe = $(`<iframe sandbox frameborder=0 scrolling="no"></iframe>`);
var contained_html_code = `<h1>Example title</h1><p>Example paragraph</p>`;
my_iframe.prop('srcdoc', contained_html_code);
Note:
There are already plenty of questions like this that have good answers, but none of them seem to work for a sandboxed iframe: I can't execute any scripts inside the iframe, and the scripts outside the iframe seem to be unable to access and read the content of the iframe. How do I make this work for a sandboxed iframe?
Bonus Points:
I only need this to be done once, when the iframe's content is set, but if you know how to write code that continuously updates the size that might be even more helpful for other people with the same problem.
Background / Why I need this:
Users of my website should be able to generate arbitrary styled html messages that can be safely displayed to other users. Since html can contain scripts, which are unsafe, these messages are packaged in an iframe.
You can use allow-same-origin sandbox attribute without allow-scripts
$(function() {
$("#testFrame").load(function() {
$(this).height($(this).contents().height());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<iframe id="testFrame" sandbox="allow-same-origin" srcdoc="<div style='height: 300px; background: red;'></div>">
</iframe>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With