Adding custom HTML and Javascript to Streamlit
02 Apr 2024Streamlit has an API to add custom HTML to your document, but the added HTML will be nested in an iframe.
Since the policies on this iframe are quite relaxed, you can use window.parent
to escape to the parent document.
This can be useful if you want access to elements on the top-level DOM.
Using the following code, the HTML added will lift itself out of its containing iframe:
from streamlit.components.v1 import html
html_contents = """
<script id="extractorScript">
let currentScript = document.getElementById('extractorScript');
window.parent.document.querySelector('iframe').insertAdjacentElement(currentScript.nextSibling);
// window.parent.document.querySelector('iframe').remove();
</script>
<div>
<h1>Test contents</h1>
<p>The HTML contents that you want to move out of its iframe</p>
</div>
"""
html(html_contents)
Prepending the contents of the script
tag to your HTML tag (a div
in this case) allows it to find the content that needs to be lifted with the .nextSibling
attribute.
If you’re planning to use this code snippet more than one time, you will have multiple iframe
elements.
In that case it’s wise to come up with a more specific CSS selector than 'iframe'
.