Simpler method to send value from javascript to python

I’ve used a st.components.v1.iframe to integrate an authentication mechanism that sends back a token to the parent if the user is allowed to authenticate, the iframe content looks like this:

    <script src="remote/auth.js"></script>
    <script>
      token = window.getAuth();
      parent.postMessage(token, '*');
    </script>

and in the streamlit app:

from streamlit.components.v1 import html, iframe
html("""
<script>
    parent.window.addEventListener('message', e => {
        const key = e.message ? 'message' : 'data';
        const token = e[key];
        parent.window.token = token;
    },false);
</script>
""")
iframe("RemoteIframeLocation")

Now what I want is to send back the parent.window.token to the python back-end in order to grant access to users based on the token.

I’m aware that basically this should be possible with bi-directional streamlit components, but it seems like it’s way too complicated and an overkill for my use case where I only need to send one value !

1 Like

Hi @Abdelgha_4,

If you are able to retrieve the token, perhaps you can use f-strings to combine the token with your Python statements.

Best regards,
Chanin

Hello, thank you for your response

Actually since the token is generated at js side (front end) there is no way that f-strings in the backend would be able to read it.

The main problem is how to communicante the token generated in the iframe back to python backend.

Hello All,

I’ve found a solution to this issue using the streamlit_javascript package:

while True:
    return_value = st_javascript('parent.window.token')
    if return_value:
        break
    time.sleep(1)
2 Likes

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