开发者

Which is a better way to detect a client's user-agent?

I am interested if which would be the best place to detect the client's user-agent, client-side (javascript) or server-side? I brought up the question due to the fact that some IE8 users are getting a m开发者_StackOverflow社区essage saying they're using IE6.


The short and correct answer is : do not use anything that relies on UserAgent sniffing.

To reliable be able to adjust code paths you should test for the specific 'thing' that the codepath is adjusted for, primarily features. This is called Feature Detection.

So if feature X is supported we do this, if not we do that.

Deducing if a feature is supported based on which UserAgent is present will rapidly fail, especially when new browsers come to the marked.
Take the following example, which can actually be found in several major libraries (!)

if (isIE8) {
    // use new feature provided by IE8
} else if (isIE7) {
    // use not so new feature provided by IE7 (and IE8)
} else {
    // use fallback for all others (which also works in IE7 and IE8)
}

What do you think happens when IE9 comes along?

The correct pattern in this case would be

if ("addEventListener" in foo) {
    // use DOM level 2 addEventListener to attach events
    foo.addEventListener(...
} else if ("attachEvent" in foo) {
    // use IE's proprietary attachEvent method
    foo.attachEvent(...
} else {
    // fall back to DOM 0
    foo["on" + eventName] = ....
}


The User-agent available on both sides should be the same, unless there's funny stuff going on, which normally isn't.

If you want to show a message to IE6 users, I suggest you use conditional comments. They're an IE-specific feature and work very well for detecting IE versions.


The information found through client or server-side detection is basically the same.

Keep in mind it is extremely easy to spoof what browser you're in. There is no fail-safe way to detect all browser types accurately.


i don't know how you're checking for the user agent, but i'd do this way:

<%=
case request.env['HTTP_USER_AGENT']
when /Safari/
    "it's a Mac!"
when /iPhone/
    "it's a iPhone"
else
    "i don't know :("
end
%>

checking directly in the user request seems to be the most consistent way to verify the user browser. And the request.env is avaliable in your controller and views, so you could pass this to rjs if needed.


For those who need to get the actual user-agent using JavaScript, you can use navigator.userAgent

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜