How to create a Copy Button that works on cloud (for multiple users on their computer)

Hi everyone,
I would like to ask if it is possible to create a button to copy certain text that can be used for users on their own computer.
I’m using “pyperclip.copy(content)” currently, but only the person who opens the website can copy successfully :cry:
Thanks!

Hello @kellyhsu,

Can you please try this to create a copy-to-clipboard button:

import streamlit as st

def create_copy_button(text_to_copy):
    button_id = "copyButton" + text_to_copy
    
    button_html = f"""<button id="{button_id}">Copy</button>
    <script>
    document.getElementById("{button_id}").onclick = function() {{
        navigator.clipboard.writeText("{text_to_copy}").then(function() {{
            console.log('Async: Copying to clipboard was successful!');
        }}, function(err) {{
            console.error('Async: Could not copy text: ', err);
        }});
    }}
    </script>"""
    
    st.markdown(button_html, unsafe_allow_html=True)

text_to_copy = "Hello, Streamlit!"
st.text_input("Text to copy:", value=text_to_copy, key="text_to_copy")
create_copy_button(st.session_state.text_to_copy)

Hope this helps!

Kind Regards,
Sahir Maharaj
Data Scientist | AI Engineer

P.S. Lets connect on LinkedIn!

➤ Want me to build your solution? Lets chat about how I can assist!
➤ Quick, practical management advice to leverage data and AI: Subscribe on LinkedIn
➤ Join my Medium community of 30k readers! Sharing my knowledge about data science and AI
➤ Website: https://sahirmaharaj.com
➤ Email: sahir@sahirmaharaj.com
➤ 100+ FREE Power BI Themes: Download Now

1 Like