Check client platform: Desktop or Mobile

Does anyone have a solution to check what platform the client is being displayed on?
Knowing this would give me the opportunity to change the form design of a few forms to improve the user’s experience on mobile devices.

Thanks in advance.

2 Likes

Something like this?

https://learn.jquery.com/code-organization/feature-browser-detection/

You could create a JS function in Native Libraries and call it from python -

https://anvil.works/docs/client/javascript

JQuery is loaded by Anvil so is already available for you to use.

3 Likes

@rickhurlbatt or anyone, did you try this out?

It would be great if anyone has an example to share.

Sorry @stein this is still on the very long to do list

@stein - here’s one way you might go about it:
take a look at stackoverflow for the question in javascript:

and then adapt a solution using anvil.js.window

the most popular answer in stackoverflow can be adapted as follows:

from anvil.js.window import navigator
import re
mobile_devices = "Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini"
is_mobile = re.search(mobile_devices, navigator.userAgent) is not None

9 Likes

Excellent, that did the trick. Thanks @stucork!

The true way to do it is to check check CSS hover is possible, mobile devices cannot do that.

2 posts were split to a new topic: Detecting whether anvil is running in the browser (typing)

Just some further information for anyone reading this down the track. It looks as there is a new way of detecting a mobile device that is being phased in to replace the unwieldy use of the userAgent string. As per this documentation there is now a boolean attribute of userAgentData which detects whether the device is mobile.

From the Docs (referencing Java Script):

# If you are checking for mobile or desktop, use the boolean mobile value:
const isMobile = navigator.userAgentData.mobile;

If I am not mistaken, this would be the Anvil way to approach this

from anvil.js.window import navigator
is_mobile = navigator.userAgentData.mobile
3 Likes

This is very cool - good find!

It looks like this is mostly but not entirely supported. See here:

Specifically it looks like Firefox, Internet Explorer, and Safari do not implement this attribute, so I’d suggest a try-except just in case. I usually use window.innerWidth <= 640 as a check.

2 Likes