├── MANIFEST.in ├── setup.py ├── LICENSE ├── example.py ├── README.md └── streamlit_js_eval ├── __init__.py └── index.html /MANIFEST.in: -------------------------------------------------------------------------------- 1 | recursive-include streamlit_* * 2 | include README.md 3 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import setuptools 2 | import pathlib 3 | 4 | component_name = "streamlit_js_eval" 5 | 6 | # See https://docs.streamlit.io/library/components/publish 7 | # rm -rf dist/;python3 setup.py sdist bdist_wheel;twine upload dist/* 8 | setuptools.setup( 9 | name=component_name, 10 | version="0.1.7", 11 | description="A custom Streamlit component to evaluate arbitrary Javascript expressions.", 12 | long_description=pathlib.Path('README.md').read_text(), 13 | long_description_content_type="text/markdown", 14 | packages=setuptools.find_packages(), 15 | include_package_data=True, 16 | author='Alireza Ghasemi', 17 | author_email='ghasemi.a.ir@gmail.com', 18 | url='https://github.com/aghasemi/streamlit_js_eval', 19 | install_requires=["streamlit>=1.0.0"], 20 | keywords=['Python', 'Streamlit', 'JavaScript'], 21 | python_requires=">=3.8", 22 | ) -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022-2024 Alireza Ghasemi 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /example.py: -------------------------------------------------------------------------------- 1 | import streamlit as st 2 | from streamlit_js_eval import streamlit_js_eval, copy_to_clipboard, create_share_link, get_geolocation 3 | import json 4 | 5 | st.write(f"User agent is _{streamlit_js_eval(js_expressions='window.navigator.userAgent', want_output = True, key = 'UA')}_") 6 | 7 | st.write(f"Screen width is _{streamlit_js_eval(js_expressions='screen.width', want_output = True, key = 'SCR')}_") 8 | 9 | st.write(f"Browser language is _{streamlit_js_eval(js_expressions='window.navigator.language', want_output = True, key = 'LANG')}_") 10 | 11 | st.write(f"Page location is _{ streamlit_js_eval(js_expressions='window.location.origin', want_output = True, key = 'LOC')}_") 12 | 13 | # Copying to clipboard only works with a HTTP connection 14 | 15 | copy_to_clipboard("Text to be copied!", "Copy something to clipboard (only on HTTPS)", "Successfully copied" , component_key = "CLPBRD") 16 | 17 | # Share something using the sharing API 18 | create_share_link(dict({'title': 'streamlit-js-eval', 'url': 'https://github.com/aghasemi/streamlit_js_eval', 'text': "A description"}), "Share a URL (only on mobile devices)", 'Successfully shared', component_key = 'shdemo') 19 | 20 | if st.checkbox("Check my location"): 21 | loc = get_geolocation() 22 | st.write(f"Your coordinates are {loc}") 23 | 24 | if True: 25 | x = streamlit_js_eval(js_expressions='window.innerWidth', key='WIDTH', want_output = True,) 26 | st.write(f"Width is {x}") 27 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Streamlit-JS-Eval 2 | 3 | [![PyPI version](https://badge.fury.io/py/streamlit_js_eval.svg?service=github)](https://badge.fury.io/py/streamlit_js_eval) [![Downloads](https://static.pepy.tech/badge/streamlit-js-eval?service=github)](https://static.pepy.tech/badge/streamlit-js-eval) 4 | [![Streamlit App](https://static.streamlit.io/badges/streamlit_badge_black_white.svg)]([https://share.streamlit.io/streamlit/corp/main](https://aghasemi-streamlit-js-eval-example-yleu91.streamlitapp.com/)) 5 | 6 | 7 | SJE is a custom Streamlit component, built to evaluate arbitrary Javascript expressions and return the result. It can become useful in doing certain functionalities which are _simple_ things in JavaScript, but unavailable or difficult to do in Streamlit. Examples include cookie management, writing to clipboard, getting device width (e.g. to check if we are on a mobile device), getting browser language, sharing something through Android's share feature, knowing user agent, etc. See [MDN docs](https://developer.mozilla.org/en-US/docs/Web/API) for more information about Web APIs. 8 | 9 | - _Version 0.1.7 - March 2024_: Proposed a workaround for issue #2. 10 | 11 | 12 | ## Install 13 | 14 | ```python 15 | pip3 install streamlit_js_eval 16 | ``` 17 | 18 | ## Example 19 | 20 | ```python 21 | st.write(f"Screen width is {streamlit_js_eval(js_expressions='screen.width', key = 'SCR')}") 22 | ``` 23 | `key` is an arbitrary but unique string, required by Streamlit components API for each call to `streamlit_js_eval`. 24 | 25 | ### Common JavaScript functionalities 26 | 27 | Some more common functionalities are already implemented as Python functions. Examples include: 28 | 29 | ```python 30 | # Returns user's location after asking for permission when the user clicks the generated link with the given text 31 | location = get_geolocation() 32 | # The URL parts of the page 33 | location_json = get_page_location() 34 | ``` 35 | 36 | See `streamlit_js_eval/__init__.py` for more functions. Check a demo in `example.py` or [see it live](https://aghasemi-streamlit-js-eval-example-yleu91.streamlitapp.com/). 37 | 38 | ## Known Limitations 39 | 40 | - It seems SJE has issues with `st.button` when getting called from inside a branch in Streamlit (e.g. in a loop, `if-else` block, ...). In version 0.1.7, you may use the custom `bootstrapButton` as a workaround in such situations. 41 | -------------------------------------------------------------------------------- /streamlit_js_eval/__init__.py: -------------------------------------------------------------------------------- 1 | import streamlit.components.v1 as components 2 | import json, os 3 | 4 | absolute_path = os.path.dirname(os.path.abspath(__file__)) 5 | frontend_path = absolute_path 6 | 7 | streamlit_js_eval = components.declare_component( 8 | "streamlit_js_eval", 9 | path=frontend_path 10 | ) 11 | 12 | def set_cookie(name, value, duration_days, component_key=None): 13 | js_ex = f'setCookie(\'{name}\', \'{value}\', {duration_days})' 14 | if component_key is None: component_key=js_ex 15 | return streamlit_js_eval(js_expressions=js_ex, key = component_key ) 16 | 17 | def get_cookie(name, component_key=None): 18 | if component_key is None: component_key=f'getCookie_{name}' 19 | return streamlit_js_eval(js_expressions=f'getCookie(\'{name}\')', key = component_key) 20 | 21 | def get_user_agent(component_key=None): 22 | if component_key is None: component_key='UA' 23 | return streamlit_js_eval(js_expressions=f'window.navigator.userAgent', key = component_key) 24 | 25 | def copy_to_clipboard(copiedText, linkText, successText, component_key=None): 26 | js_text = ''' 27 | setFrameHeight(100); 28 | document.getElementsByTagName("body")[0].innerHTML += `%s`; 29 | 30 | document.getElementById("cbc").addEventListener("click", function() { 31 | console.log('Copying') 32 | const copiedText = `%s` 33 | copyToClipboard(copiedText, () => document.getElementById("cbc").innerHTML = '%s' ); 34 | 35 | }) 36 | '''%(str(87264), linkText, copiedText, successText) 37 | if component_key is None: component_key=f'{linkText}{copiedText}{successText}' 38 | return streamlit_js_eval(js_expressions=js_text, key = component_key) 39 | 40 | def bootstrapButton(title,component_key=None): 41 | return streamlit_js_eval(js_expressions=f"bsButton('{title}')", key=component_key if component_key is not None else title) 42 | 43 | def get_geolocation(component_key=None): 44 | js_text = 'getLocation()' 45 | if component_key is None: component_key=js_text 46 | return streamlit_js_eval(js_expressions=js_text, key = component_key) 47 | 48 | def get_browser_language(component_key=None): 49 | if component_key is None: component_key='LANG' 50 | return streamlit_js_eval(js_expressions=f'window.navigator.language', key = component_key) 51 | 52 | def get_page_location(component_key=None): 53 | if component_key is None: component_key='LOC' 54 | location_str = streamlit_js_eval(js_expressions='JSON.stringify(window.location)', key = component_key) 55 | if location_str is not None: 56 | return json.loads(location_str) 57 | return None 58 | 59 | 60 | def create_share_link(sharedObject, linkText, successText, component_key=None): 61 | js_text = ''' 62 | setFrameHeight(100); 63 | document.getElementsByTagName("body")[0].innerHTML += `%s`; 64 | 65 | document.getElementById("shli").addEventListener("click", function() { 66 | console.log('Sharing') 67 | if (navigator.share) { 68 | navigator.share(%s).then(() => { 69 | document.getElementById("shli").innerHTML = '%s' 70 | console.log('Thanks for sharing!'); 71 | }) 72 | .catch(console.error); 73 | } else { 74 | console.log('Sharing failed') 75 | } 76 | }) 77 | '''%(str(87264), linkText, sharedObject, successText) 78 | 79 | if component_key is None: component_key=f'{linkText}{sharedObject}{successText}' 80 | 81 | return streamlit_js_eval(js_expressions=js_text, key = component_key) 82 | -------------------------------------------------------------------------------- /streamlit_js_eval/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 151 | 152 | 153 | --------------------------------------------------------------------------------