Spaces:
Sleeping
Sleeping
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(); | |
// Send the result back to Streamlit | |
window.parent.postMessage({ isStreamlitMessage: true, type: 'streamlit:js_return', data: result }, '*'); | |
} | |
// Add an event listener to listen for 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 to display 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> | |
// Trigger the JavaScript function via a postMessage event | |
window.parent.postMessage({ type: 'streamlit:buttonClick' }, '*'); | |
</script> | |
""" | |
html(trigger_js, height=0) | |
# Add a listener for JavaScript responses | |
st.markdown( | |
""" | |
<script> | |
// Listen for messages from JavaScript | |
window.addEventListener('message', (event) => { | |
if (event.data && event.data.type === 'streamlit:js_return') { | |
// Pass the data back to Streamlit as a new message | |
const result = event.data.data; | |
document.dispatchEvent(new CustomEvent('StreamlitResult', { detail: result })); | |
} | |
}); | |
// Dispatch data from CustomEvent to Streamlit | |