简体   繁体   中英

Javascript detect if on mobile device

Okay, this has been answered many times before, but it's not working for me. I'm using navigator.userAgent and searching for certain words android|iphone|kindle|ipad. But this doesn't work. When I run on my mobile, userAgent is:

Mozilla/5.0 (Linux: Android 12) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/105.0.5195.79 Mobile DuckDuckGo/5 Safari/537.36

So that works, but when I play on my laptop userAgent is:

Mozilla/5.0 (Linux: Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Mobile Safari/537.36 Edg/105.0.1343.33

So the method I'm using both pick up on "Android" and so both mobile and laptop trigger as mobile.

Is there a different method, or a better way of doing this?

Thanks.

I guess this is a Chrome exception (version 15 and 16). In Firefox and MS Edge I don't have this problem.

So I made a workaround to make a temporary quick fix:

(... code before with my toMatchItem to mobile and then)

// Chrome browser exception
let isChrome = navigator.userAgent.match(/chrome|chromium|crios/i);
let isChromeException = navigator.userAgent == 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Mobile Safari/537.36';

return toMatch.some((toMatchItem) => navigator.userAgent.match(toMatchItem)) && !(isChrome && isChromeException);

Add this on to your mobile condition this condition: && !(isChrome && isChromeException)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM