I need to pass information back from JavaScript to Python. Is there a way to do this. After looking through forums and googling, I haven’t found an answer yet.
What I really want is to call a python function, run some JavaScript, set a value for a python variable and return that value. If I cant get that, I would try for setting session state information but so far, that hasn’t worked and I’m out of ideas.
import streamlit as st
import streamlit.components.v1 as components
def main():
st.title("JavaScript to Python Communication")
# HTML and JavaScript component
html_code = """
<div>
<input type="text" id="messageInput" />
<button onclick="sendMessage()">Send to Streamlit</button>
<script>
function sendMessage() {
const message = document.getElementById('messageInput').value;
// Use Streamlit's JavaScript API to pass data
window.parent.postMessage({
type: 'streamlit:custom-component-message',
key: 'js_message',
data: message
}, '*');
window.location.reload();
console.log('message', message);
setTimeout(3000);
}
</script>
</div>
"""
# Render the HTML component
components.html(html_code, height=100)
# Check for any messages from JavaScript
if 'js_message' in st.session_state:
message = st.session_state['js_message']
st.write(f"Received message: {message}")
# Process the message as needed
st.write(f"Processed message: {message.upper()}")
if __name__ == "__main__":
main()