Friday, June 12, 2026

Streamlit Add Copy Button

import streamlit as st
from streamlit.components.v1 import html

text = """Try out a limited version of Streamlit right in your browser. Just edit the code below and the app on the right updates automatically. For the real thing, install our Python library."""

st.code(body = text,
        language = "markdown", wrap_lines=True, line_numbers=False)

st.caption(f"""```diff
    + {text}
    """, help=None)

html_js = f"""
<span id="highlight" style='color: green;'>{text}</span> 
<button onclick="copyToClipboard()">Copy</button>
<script>
function copyToClipboard() {{
const high = document.getElementById("highlight");
navigator.clipboard.writeText(high.textContent).then(() => {{
alert("Copied: " + high.textContent);
}}).catch(err => {{
console.error("Failed to copy text: ", err);
}});
}}
</script>
"""
st.html(html_js)
html(html_js)