Spaces:
Sleeping
Sleeping
| import streamlit as st | |
| from streamlit.components.v1 import html | |
| def main(): | |
| st.title("Copy Text Demo") | |
| st.write("This demo shows how to copy text from an HTML textarea into Streamlit.") | |
| # HTML component with textarea and copy button | |
| html_code = """ | |
| <textarea id="myTextarea" rows="5" style="width: 100%; padding: 10px; margin: 10px 0;">Here is some sample text that you can copy. | |
| Try modifying this text and clicking the Copy button below!</textarea> | |
| <button onclick="copyToStreamlit()" style="padding: 8px 16px; background-color: #ff4b4b; color: white; border: none; border-radius: 4px; cursor: pointer;"> | |
| Copy to Streamlit | |
| </button> | |
| <script> | |
| function copyToStreamlit() { | |
| const text = document.getElementById('myTextarea').value; | |
| window.parent.postMessage({ | |
| type: 'streamlit:message', | |
| data: { | |
| type: 'copyText', | |
| text: text | |
| } | |
| }, '*'); | |
| } | |
| // Listen for messages from Streamlit | |
| window.addEventListener('message', function(event) { | |
| if (event.data.type === 'streamlit:render') { | |
| // Component has been re-rendered | |
| console.log('Component rendered'); | |
| } | |
| }); | |
| </script> | |
| """ | |
| # Create a placeholder for the copied text | |
| if 'copied_text' not in st.session_state: | |
| st.session_state.copied_text = None | |
| # Render HTML component | |
| html(html_code, height=200) | |
| # JavaScript message handler | |
| st.markdown(""" | |
| <script> | |
| window.addEventListener('message', function(event) { | |
| if (event.data.type === 'copyText') { | |
| const text = event.data.text; | |
| window.streamlitMessageListener.handleMessage({ | |
| type: 'streamlit:setComponentValue', | |
| value: text | |
| }); | |
| } | |
| }); | |
| </script> | |
| """, unsafe_allow_html=True) | |
| # Display copied text in a code block if available | |
| if st.session_state.copied_text: | |
| st.subheader("Copied Text:") | |
| st.code(st.session_state.copied_text, language='text') | |
| if __name__ == "__main__": | |
| main() |