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.
pip install streamlit-javascriptVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to use `st_javascript` to execute both asynchronous JavaScript (e.g., an `fetch` API call) and synchronous JavaScript (e.g., retrieving `window.innerWidth`). The `st_javascript` function returns the result of the JavaScript execution, which can be `None` on initial page load or before the JavaScript completes.
For complex JavaScript interactions, ensure your JavaScript explicitly uses `return` for the final value. For custom components outside of `st_javascript`, use `window.parent.postMessage()` to send data back to Python. `st_javascript` is designed to capture the return value of the provided JS string directly.
Cast the `st_javascript` result to the desired type, e.g., `int(return_value)` or `bool(return_value)`. For JSON objects, `st_javascript` attempts to parse it into a Python dict, but verify its type.
If encountering unexpected parsing errors, try moving the entire JavaScript snippet to the first line within the `st_javascript` function's argument, or ensure it's a compact, single-line expression.
Use Streamlit's `st.session_state` to store and conditionally execute JavaScript, or leverage `st.cache_data`/`st.cache_resource` for parts of your app that should not re-render constantly. Be mindful of JavaScript side effects upon repeated execution.
Explicitly 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'}"))`.Run `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.
Thoroughly 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.
No resource links recorded.