Detect whether code is being run from mobile

Hello,

Here is my solution in a few line of code after having installed the correct module

pip install streamlit-javascript
pip install pyyaml ua-parser user-agents

After that in your main code


from streamlit_javascript import st_javascript
from user_agents import parse

.....
main()

ua_string = st_javascript("""window.navigator.userAgent;""")
user_agent = parse(ua_string)
st.session_state.is_session_pc = user_agent.is_pc
st.info(st.session_state.is_session_pc)        

user_agent.is_pc returns True if the session runs on a PC. I then used that to conditionally render some data or not if the User is not running from a PC.

Can also potentially help to prevent the execution of your Streamlit Apps by Bots or other automatic agents.

:bulb: More info on the packages installed here:

Hope this will be helpful! :pray:
Cheers,
Pascal

4 Likes