Detect whether code is being run from mobile

Is it possible for code to detect whether the browser is on a phone or small display?

There is a table in our app which seen from mobile looks terrible. We would like to detect if mobile browser is active, and reorganize rows into cards that you can swipe down conveniently.

Is there a variable we can use in the code to know the environment the code is being executed on so we can tailor the UX to it?

2 Likes

Bump - interested in ideas here. This feels like a very common case, and haven’t seen conclusive resolution searching in the forums.

Is there a way for python code to be aware of what UX context is it being run in?

It would be ultra helpful to change layouts for mobile apps, or even yet, to create mobile-first streamlit mobile apps.

Also interested in this feature.

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

3 Likes

I made this component specifically for this:

streamlit-browser-engine
github, pypi, demo

Output:

1 Like