[英]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? 我感兴趣的是哪个是检测客户端的用户代理,客户端(javascript)或服务器端的最佳位置? I brought up the question due to the fact that some IE8 users are getting a message saying they're using IE6.
我提出这个问题是因为一些IE8用户正在收到消息说他们正在使用IE6。
The short and correct answer is : do not use anything that relies on UserAgent sniffing. 简短而正确的答案是:不要使用任何依赖于UserAgent嗅探的东西。
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. 因此,如果支持功能X,我们会这样做,如果不是,我们会这样做。
Deducing if a feature is supported based on which UserAgent is present will rapidly fail, especially when new browsers come to the marked. 如果基于哪个UserAgent支持某项功能,则推断将很快失败,尤其是当新浏览器进入标记时。
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? 当IE9出现时,您认为会发生什么?
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 . 如果您想向IE6用户显示消息,我建议您使用条件 注释 。 They're an IE-specific feature and work very well for detecting IE versions.
它们是IE特有的功能,非常适合检测IE版本。
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.
request.env在您的控制器和视图中是可用的,因此您可以根据需要将其传递给rjs。
对于需要使用JavaScript获取实际用户代理的用户,可以使用navigator.userAgent
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.