awacke1's picture
Update app.py
b30a75c verified
raw
history blame
2.44 kB
import streamlit as st
from streamlit.components.v1 import html
# Define JavaScript code
javascript_code = """
<script>
// Function to return a string
function myJavaScriptFunction() {
return "Hello from JavaScript!";
}
// Function to call and send data back to Python
function callAndCapture() {
const result = myJavaScriptFunction();
window.parent.postMessage({ isStreamlitMessage: true, type: 'streamlit:js_return', data: result }, '*');
}
// Add event listener to handle messages from Streamlit
window.addEventListener('message', function(event) {
if (event.data && event.data.type === 'streamlit:buttonClick') {
callAndCapture();
}
});
</script>
<button onclick="callAndCapture()">Run JavaScript Function</button>
"""
# Embed JavaScript into Streamlit app
html(javascript_code, height=300)
# Placeholder for displaying results
result_placeholder = st.empty()
# Add Streamlit button to trigger JavaScript function
if st.button("Call JavaScript Function"):
st.write("Waiting for JavaScript response...")
trigger_js = """
<script>
window.parent.postMessage({ type: 'streamlit:buttonClick' }, '*');
</script>
"""
html(trigger_js, height=0)
# Listener for JavaScript messages
st.markdown(
"""
<script>
// Function to listen for messages from JavaScript
window.addEventListener('message', (event) => {
if (event.data && event.data.type === 'streamlit:js_return') {
const result = event.data.data;
// Send the result to Streamlit via a custom event
document.dispatchEvent(new CustomEvent('StreamlitResult', { detail: result }));
}
});
// Dispatch result to Streamlit when received
document.addEventListener('StreamlitResult', (e) => {
const data = e.detail;
window.parent.postMessage({ type: 'streamlit:result', data: data }, '*');
});
</script>
""",
unsafe_allow_html=True,
)
# Handle the result sent from JavaScript
if "js_result" not in st.session_state:
st.session_state["js_result"] = ""
# Update session state and display the result
try:
received_result = st.session_state["js_result"]
# Only display if we have new data
if received_result:
result_placeholder.write(f"Result from JavaScript: {received_result}")
except Exception as e:
st.error(f"An error occurred: {e}")