Detect phone/tablet/web client using javascript

后端 未结 4 1810
闹比i
闹比i 2020-12-17 01:08

I am trying to detect if the end user is on a phone, a tablet or a pc

I have been Googling for a while, apparently there are no easy solution.

Well I guess I

相关标签:
4条回答
  • 2020-12-17 01:27

    I'd recommend looking into media queries and the <viewport> tag.

    Some excellent articles on the thought processes behind responsive design.

    http://www.html5rocks.com/en/mobile/mobifying/

    http://www.magazine.org/timecom-gm-craig-ettinger-bringing-responsive-web-design-iconic-brand

    The question remains, what are you trying to accomplish?

    0 讨论(0)
  • 2020-12-17 01:37

    Yes, you should not rely on resolution or orientation. But how about em-based media queries?

    In order to read the results of your media query with javascript, you could try adding a media query to your css to add invisible content to your page:

    @media all and (max-width: 45em) {
        body:after {
            content: 'smallscreen';
            display: none;
        }
    }
    

    Then read the content through javascript:

    var size = window.getComputedStyle(document.body,':after').getPropertyValue('content');
    

    Then determine what you want to load:

    if (size.indexOf('smallscreen') !=-1) {
        // Load some content for smaller screens.
    }
    
    0 讨论(0)
  • 2020-12-17 01:39

    Quick answer why match of agent does not work against the given list: "Android" is not in the returned (agent) string! Just assume that NONE of the given strings are correct and liars abound.

    I have posted tested code proving the android case.

    0 讨论(0)
  • 2020-12-17 01:43

    User Agents are pretty unreliable, and can actually be faked by clients. I would recommend to focus on specific functionality instead of specific devices. Modernizer is a library that can be used to detect if features are available on the client device. This will allow you to detect if things like local storage, etc are available. If you are interested in something like Responsive Web Design instead of device/client specific features, you could use a library like Twitter's Bootstrap. At the bottom of the Scaffolding page, it even has some features that enable detection of phone vs. tablet vs. desktop, although I believe that it is based on resolution.

    --Edit to add--

    I would also like to emphasize that you should ask yourself why you actually care what device the user is on. It will be much easier to detect the specific feature you care about than it will be to detect all features that are available.

    0 讨论(0)
提交回复
热议问题