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