How to embed javascript into streamlit?

have a streamlit app that i want to embed into it javascript i already add html tags by using st.markdown() and i was able to add some bootstrap but when i tried to add javascript code above the html tags it crashes.

So how this can be done within streamlit ?

Hi - Use components.html.

1 Like

How to use it ?
I saw a video about it but i did not clearly understand where to put the js script.

Hi! A minimum working example could be:

import streamlit as st
from streamlit.components.v1 import html

# Define your javascript
my_js = """
alert("Hola mundo");
"""

# Wrapt the javascript as html code
my_html = f"<script>{my_js}</script>"

# Execute your app
st.title("Javascript example")
html(my_html)

Piece of advice: debugging javascript from streamlit is haaaaard. Work it out in a separate html, be sure it’s working, and just then copy the code back to streamlit! Chrome’s Developer Tools can be helpful, too.
(If anyone knows a better method, please advice!)

1 Like

hi, if I use like this:

import streamlit as st
from streamlit.components.v1 import html
html(f'''<input id="example" type="datetime-local"/>''')

how can I get the value of user input and give it to a python variable and print it on the page?
thank you!

Hi @BeyondMyself

I think the better/easiest way is using the simpler bidirectional component template Code snippet: create Components without any frontend tooling (no React, Babel, Webpack, etc) and building your calendar input there.

The HTML method does not send back data to Python as it only displays a static render (Doc Components API). To be honest it could be feasible to hack your way through it through JS hacks that basically revolve on rebuilding the full bidirectional function from the template, which is a bit sad :confused:

Have a nice day,
Fanilo :balloon:

3 Likes

@BeyondMyself @andfanilo

FYI, I extended the ideas in that post to make the initialization and eventing mechanisms more explicit. To demo that I implemented a simple toggle button component. Much of the JS part is easily re-useable as scaffolding in your own components.

GitHub - asehmi/streamlit-toggle-buttons-component: Pure static HTML/JS Streamlit component toggle button implementation

4 Likes

thank you.
this way is work.