Issue with postMessage: JavaScript event is not receiving in Python Streamlit Application

I’m trying to set up a communication between JavaScript and Python in my Streamlit application to handle an acknowledgment when a button is clicked in the alert. While the JavaScript function executes correctly, the acknowledgment message isn’t being received in Python’s session state.

I’ve added a postMessage call in my JavaScript, but the session state remains None. Here’s my approach. Any help would be appreciated!

def show_msg(message):
    streamlit.components.v1.html(f"""
        <div id="msgBox" style="background-color: yellow; padding: 10px;">
            <p>{message}</p>
            <button onclick="acknowledgeAlert()">Acknowledge</button>
        </div>
        <script>
        function acknowledgeAlert() {{
            const msgBox = document.getElementById('msgBox');
            msgBox.style.display = 'none'; // Hide the msgbox
            console.log('Acknowledgment button clicked');
            window.parent.postMessage('Acknowledged', '*'); 
        }}
        </script>
    """, height=100)

# Listen for messages from JavaScript
def listen_for_messages():
    if 'component_value' in st.session_state:
        if st.session_state['component_value'] == 'Acknowledged':
            st.write("Acknowledgment received in Python backend!")
            st.session_state['component_value'] = None

show_msg("Click acknowledge!")

# Listen for acknowledgment messages
while True:
        listen_for_messages()

Hi did you made it working ? please let me know the workaround

Hack this code of mine which is a pure HTML/JS implementation of components. It’s dead easy to get messages back and forth between Streamlit and simple HTML/JS apps. The power of this simple approach is better illustrated in my Sweetviz integration.

1 Like

I found the solution like if streamlit default component supports it is better to use streamlit custom component, and it was very easy to achieve the same design and callback functions as per our requirement quickly , the following vide helped me