Streamlit-Javascript Component
Streamlit-javascript is a third-party Streamlit component (current version 0.1.5) that enables Python applications to execute arbitrary JavaScript code on the client-side browser and retrieve the results back into the Streamlit script. This facilitates advanced frontend interactions and data retrieval not natively supported by Streamlit, such as accessing browser-specific properties or making client-side API calls. The library's release cadence appears to be slow, with the latest PyPI version from May 2022.
Common errors
-
TypeError: The return value of st_javascript is not what I expect (e.g., an integer is returned as a string '2', or a dict is a string)
cause `st_javascript` often returns the JavaScript result as a string, even if it represents a number, boolean, or JSON.fixExplicitly convert the returned string to the desired Python type, e.g., `my_int = int(st_javascript("2"))` or `my_dict = json.loads(st_javascript("{'key': 'value'}"))`. -
ModuleNotFoundError: No module named 'streamlit_javascript'
cause The `streamlit-javascript` library is not installed in the active Python environment or is not accessible.fixRun `pip install streamlit-javascript` in your virtual environment or global Python environment. Ensure your Streamlit application is run with the Python interpreter where the package is installed. -
JavaScript code execution fails or returns None/unexpectedly empty, especially with complex scripts or `fetch`.
cause The JavaScript code might have a syntax error, be asynchronous without being `await`ed, or might not explicitly return a value that `st_javascript` can capture.fixThoroughly debug your JavaScript code. For asynchronous operations like `fetch`, ensure you `await` the promise. Verify that the last expression in your JavaScript string produces the desired return value. Add `console.log()` statements in your JS and check the browser's developer console for errors.
Warnings
- gotcha JavaScript functions executed via `st_javascript` might sometimes return '0' or an unexpected value if `window.parent.postMessage()` is not used explicitly for custom component communication, or if the JS execution context doesn't properly return a value that `st_javascript` can capture.
- gotcha The return value from `st_javascript` is typically a string representation of the JavaScript result. If you expect a numerical or boolean type, explicit type conversion in Python is necessary.
- gotcha Some reports indicate that JavaScript code passed to `st_javascript` might be sensitive to whitespace or line breaks, potentially requiring the code to start on the very first line within the triple-quoted string.
- gotcha Streamlit re-runs the entire script on every user interaction. JavaScript code executed via `st_javascript` will also re-run, which can lead to performance issues or unexpected side effects if not managed carefully (e.g., with Streamlit's caching or session state).
Install
-
pip install streamlit-javascript
Imports
- st_javascript
import streamlit_javascript
from streamlit_javascript import st_javascript
Quickstart
import streamlit as st
from streamlit_javascript import st_javascript
st.subheader("Javascript API Call Example")
# Example 1: Making an asynchronous fetch request in JavaScript
# The result is returned to Python once the JS promise resolves.
return_value = st_javascript("""
await fetch("https://reqres.in/api/products/3")
.then(function(response) {
return response.json();
})
""")
if return_value:
st.markdown(f"Return value was: `{return_value}`")
st.write("Parsed JSON:", return_value) # Streamlit-javascript attempts to parse JSON strings into Python objects
else:
st.info("Waiting for JavaScript fetch to complete...")
st.subheader("Get Browser Window Width Example")
# Example 2: Getting a simple browser property (synchronous)
window_width = st_javascript("window.innerWidth")
if window_width:
st.write(f"Current browser window width: {window_width}px")
else:
st.info("Waiting for JavaScript to return window width...")