Passing Data Back From JavaScript to Python

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()

You would need a bidirectional component for that.

If you just want to run some JS and get a value back to the app, there is already a component that you may find useful,
https://pypi.org/project/streamlit-javascript/

This is outstanding. This will definitely get me to my desired outcome.

Thank you.

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.