can I display custom javascript in streamlit web app
Asked Answered
P

1

9

I am working on a parking data app using Streamlit library in python 3.7, I want to display the availability of parking spots using custom JavaScript for visualization. Is it possible to display HTML/javascript elements in streamlit web app

Pistareen answered 14/6, 2021 at 21:25 Comment(4)
good luck. Come back when you get error message.Higinbotham
@Higinbotham I am asking it is possible, I don't seem to find anything about it in Streamlit documentation.Pistareen
then check source code.Higinbotham
using Google streamlit add htmlI found How to render already prepared html code with Streamlit? which uses st.markdown(html_string, unsafe_allow_html=True). It think you could use it to add HTML and JavaScript. But in documentation I found Create a Streamlit Component and maybe this can be more interesting.Higinbotham
H
9

Digging in Google I found:

You can add HTML using

import streamlit as st

st.markdown(html_string, unsafe_allow_html=True)

but this can't add JavaScript.

Forum: How to render already prepared html code with Streamlit?


You can add HTML and JavaScript using

import streamlit.components.v1 as components

components.html(html_string)

but this puts it in <iframe>

Doc: Components API reference


Minimal working example

import streamlit as st
import streamlit.components.v1 as components

html_string = '''
<h1>HTML string in RED</h1>

<script language="javascript">
  document.querySelector("h1").style.color = "red";
  console.log("Streamlit runs JavaScript");
  alert("Streamlit runs JavaScript");
</script>
'''

components.html(html_string)  # JavaScript works

st.markdown(html_string, unsafe_allow_html=True)  # JavaScript doesn't work

To put directly HTML with JavaScript you would need to build Component but it seems more complex method which may need code in TypeScript.

See videos in doc: Create a Streamlit Component

Higinbotham answered 15/6, 2021 at 1:14 Comment(1)
even those custom components get rendered in an iframe: "built out of HTML and any other web tech you like (JavaScript, React, Vue, etc.), and gets rendered in Streamlit apps via an iframe tag."Foppery

© 2022 - 2024 — McMap. All rights reserved.