简体   繁体   中英

Is there an elegant way to detect mobile browsers?

I have a website that, when accessed by a mobile browser, to redirect to a different page .

I have been having trouble coming up with a way that reliably detects mobile devices. Currently, I Javascript code like this:

if (document.documentElement.clientWidth < 680 || 
    document.documentElement.clientHeight < 450) 
  location.href = "handheld.aspx";

that redirects if the broswer size is smaller than what is supported on the desktop version. The problem with this is that some mobile browsers start zoomed way out and have the similar browser dimensions as desktop devices.

I've researched this some, and I've mainly found solutions that involve sniffing the user agent sting and checking it against a bunch of strings in existing mobile devices. If possible, I'd like to avoid that route because it seems extremely messy and will break in the future when new devices come out.

Is there a less kludgy way to detect mobile browsers, or at least a more reliable way to detect screen size?

You have to decide which aspect of a mobile browser you are most trying to detect. Are you trying to detect the screen size and redirect to a site design that fits on a smaller screen. If so, you can use window.screen ( doc here ).

If you're trying to detect specific capabilities or lack of capabilities in mobile browsers, then you should use feature detection to find out whether the specified features are there or not there. This is way better than detecting browser user agents.

Detecting based on screen size is a losing battle in a world where new screen sizes are popping up left and right. You should use server-side detection and modify your view accordingly. Using a service like Device Atlas or WURFL will future-proof you and give you far more capabilities that you're likely to accomplish on your own.

For the record, JS-based mobile redirects are the worst-possible solution from a performance standpoint and should be avoided.

否。您无法检查屏幕尺寸或用户代理

If you want an easy fix for this, you can try handsetdetection javascript It gives you the ability to set rules and conditions such as screen size, vendor, OS, Browser, display width and height for your redirection. And if you are fond of statistics, HD has a great analytics reporting that you can use to fine tune how your redirection is served to your site users/visitors.

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