Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
599 views
in Technique[技术] by (71.8m points)

browser detection - Detect phone/tablet/web client using javascript

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 should not use Resolution, since nowadays some tablets have amazing resolutions.

I should not rely on orientation, because windows8 laptops can just rotate like tablets. (and responsive design is just too difficult for my current project)

I've been trying to use UserAgent(thought it has its drawbacks too), but can not get it working, below is a conjunction of different versions online that I am using to distinguish phone/tablet from PCs, they just do not work and I have no idea why

var agents = ['android', 'webos', 'iphone', 'ipad', 'blackberry','iemobile','phone','mobile'];
                for(i in agents) {
                    if(navigator.userAgent.toLowerCase().match('/'+agents[i]+'/i')) {
                        return true;
                    }
                }


if( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
                return true;
            }

 if( navigator.userAgent.match(/Android/i)
                 || navigator.userAgent.match(/webOS/i)
                 || navigator.userAgent.match(/iPhone/i)
                 || navigator.userAgent.match(/iPad/i)
                 || navigator.userAgent.match(/iPod/i)
                 || navigator.userAgent.match(/BlackBerry/i)
                 || navigator.userAgent.match(/Windows Phone/i)
                 || navigator.userAgent.match(/bada/i)
                 || navigator.userAgent.match(/Bada/i)
                 ){
                return true;
            }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...