Sealyu

--- 博客已迁移至: http://www.sealyu.com/blog

  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  618 随笔 :: 87 文章 :: 225 评论 :: 0 Trackbacks

This topic demonstrates how to detect current and future versions of Windows Internet Explorer more effectively.

This topic contains the following sections.

Introduction

Many Web designers use browser detection techniques to ensure that their sites display properly when viewed with specific browsers. Some browser detection techniques encounter problems when viewed with later versions of the browser they're tailored for. For example, many Web designers used Cascading Style Sheets (CSS) rules that relied on the implementation of CSS in Microsoft Internet Explorer 6 to detect that version of the browser. When Internet Explorer 7 provided additional support for the CSS, Level 2 (CSS2) standard, many of these rules (also known as "CSS hacks") failed to detect the new version of the browser. As a result, sites that relied on these rules no longer displayed as intended. When using browser detection techniques, use techniques that support current and future versions of the browser you're targeting.

This topic examines four different ways to detect Internet Explorer and also provides a brief look at alternatives to browser detection. Advantages of each technique are reviewed and suggestions are offered for effective use. In addition, examples demonstrate techniques that support current and future versions of Internet Explorer.

Parsing the User-Agent String

The most common way to detect Internet Explorer is to use client-side scripting to parse the user-agent string and extract the version number from the version token. The following example shows the preferred way to do this with JavaScript.

function getInternetExplorerVersion()

// Returns the version of Internet Explorer or a -1

// (indicating the use of another browser).

{

var rv = -1; // Return value assumes failure.

if (navigator.appName == 'Microsoft Internet Explorer')

{

var ua = navigator.userAgent;

var re = new RegExp("MSIE ([0-9]{1,}[".0-9]{0,})");

if (re.exec(ua) != null)

rv = parseFloat( RegExp.$1 );

}

return rv;

}

function checkVersion()

{

var msg = "You're not using Internet Explorer.";

var ver = getInternetExplorerVersion();



if ( ver > -1 )

{

if ( ver >= 8.0 )

msg = "You're using a recent copy of Internet Explorer."

else

msg = "You should upgrade your copy of Internet Explorer.";

}

alert( msg );

}

As you review this example, please note the following:

  • A regular expression extracts the version number from the user-agent version token. Regular expressions let you specify optional conditions to match, so that you can match a larger number of version tokens, not just those that match a strict set of conditions.

  • The version number extracted from the version token is formally converted to a numeric value. Care must be taken because pre-release versions of Internet Explorer typically add letters to the version token. For example, the version token for pre-release versions of Internet Explorer 7 was "MSIE 7.0b."

  • The checkVersion() function verifies that the browser is version 8.0 or later. This ensures that the welcome message is displayed for those using newer versions of the browser.

This example properly detects most versions of Internet Explorer, but only if scripting is enabled. However, the user-agent string is dynamic; it can be changed by the end user, by browser extensions, and by operating system updates. As a result, there's no guarantee that the user-agent string accurately reflects the browser being used. The next sections show techniques that may be more effective alternatives.

Note  It is not recommended that you block access to content based on the user-agent string of the browser. If you do have to offer different content to different versions of the browser due to improved capabilities, you want to ensure that future versions of the browser are not blocked. Serving content based solely on the user-agent string is often an unreliable way to detect the full capabilities of the browser.

For more information about the user-agent string and Internet Explorer's user-agent tokens, see Understanding User-Agent Strings.

Using Conditional Comments

If you are specifically interested in Internet Explorer, conditional comments might be a more appropriate choice. The following example shows an effective way to use conditional comments to display custom content.

<!--[if gte IE 8]>

<p>You're using a recent version of Internet Explorer.</p>

<![endif]-->



<!--[if lt IE 7]>

<p>Hm. You should upgrade your copy of Internet Explorer.</p>

<![endif]-->



<![if !IE]>

<p>You're not using Internet Explorer.</p>

<![endif]>

Like the earlier JavaScript example, this example makes sure the current version is greater than or equal to a specified version number. This ensures that the content designed for the current version of the browser is properly displayed in a future version.

This example carefully combines downlevel-revealed and downlevel-hidden conditional comments to ensure that each message appears only for the intended browsers.

Because conditional comments do not rely on JavaScript, they are effective even if the user has disabled scripting. Unlike the user-agent string, conditional comments are typically updated when the browser is upgraded. This makes them more reliable than user-agent strings. However, because no other browser currently supports conditional comments, they are limited to Internet Explorer. Depending on your needs, this may be an advantage or a disadvantage.

For more information about conditional comments, see About Conditional Comments.

Detecting Features

For many Web sites, detecting a browser's features is the preferred form of browser detection because it allow the Web developer to focus on the general capabilities of a browser, rather than the specific details of each browser release. The following example demonstrates a simple form of feature detection.

if (XMLHttpRequest)

{

// This browser implements this feature.

}

Feature detection tends to support a broader range of browsers. In addition, should a browser implement the feature you're interested in, your content will be delivered without requiring changes to your browser detection technique. As a result, techniques that focus on features tend to require less maintenance than techniques that rely on environmental factors, such as the user-agent string. In addition, they tend to work across a wider variety of browser devices, including screen readers, mobile devices, and so on.

Use care when creating or using browser detection techniques that attempt to detect a browser based on unsupported functionality. If a future version of the browser implements the missing feature, it's entirely possible your site may not display as intended.

Using the ASP.NET HttpBrowserCapabilities Object

ASP.NET developers can use the HttpBrowserCapabilities object to detect and respond to almost any browser. In addition, alternate content is not sent to the end-user's browser. The following example shows how to detect Internet Explorer from an ASP.NET application using C#.

private float getInternetExplorerVersion()

{

// Returns the version of Internet Explorer or a -1

// (indicating the use of another browser).

float rv = -1;

System.Web.HttpBrowserCapabilities browser = Request.Browser;

if (browser.Browser == "IE")

rv = (float)(browser.MajorVersion + browser.MinorVersion);

return rv;

}



private void Page_Load(object sender, System.EventArgs e)

{

string msg;

double ver = getInternetExplorerVersion();

if (ver > 0.0)

{

if (ver >= 7.0)

msg = "You're using a recent version of Internet Explorer.";

else

msg = "You should upgrade your copy of Internet Explorer.";

}

else

msg = "You're not using Internet Explorer.";



Label1.Text = msg;

}

Because the HttpBrowserCapabilities object parses the user-agent string for you, you can use the MajorVersion and MinorVersion properties to determine the current version of the browser. Unlike the JavaScript examples, these properties are numeric; MajorVersion returns an integer value, and MinorVersion returns a double value. Depending on the language used to implement your ASP.NET application, however, you might still have to typecast these property values to the data type you're using. To illustrate, the C# example converts MajorValue to the floating point value returned by the function.

For more information about the HttpBrowserCapabilities object, see HOW TO: Determine the Browser Version in ASP.NET or Browser Sniffing in ASP.NET World Wide Web link.

Alternatives to Browser Detection

If you use browser detection because Internet Explorer doesn't appear to support a particular feature, an alternate approach may be more effective. Before implementing new (or revising existing) browser detection, it may be worthwhile to consider one of the following approaches to solve the underlying problem.

  • Internet Explorer allows Web developers to choose between various document compatibility modes that affect the way the browser interprets and displays content. If you are not seeing the results you expect, a different document compatibility mode may provide the results you seek. For more information, see Defining Document Compatibility.

    You may want to consider using the Developer Tools to preview your pages in different document compatibility modes or to experiment with different ways to achieve various visual and layout effects. It's entirely possible there's another way to accomplish the same result.

  • If the Document Object Model (DOM) doesn't support a feature that you need, you may be able to add the feature using DOM mutable prototypes.

  • If none of the previous suggestions apply, it may be worthwhile to consider using an alternate approach.

Summary

If you must detect the browsers that view your Web sites, follow effective practices: plan for future browser releases, convert values appropriately, and design techniques to fail gracefully. Doing so will reduce the long-term maintenance of your site and help ensure that your site functions properly when viewed with newer versions of Internet Explorer and other browsers.

Community Content
Annotations
Bad browser detection
Using "v to detect IE is a bad idea because this will not work if future versions of IE change this behavior. The officially supported detection methods should be used.

However this example from the article is misleading. Since other browsers don't support conditional comments [if !IE] results in comments that will show up in no browsers.
<![if !IE]>
<p>You're not using Internet Explorer.</p>
<![endif]>

How to detect IE8 using JavaScript
Check out:
http://blogs.msdn.com/giorgio/archive/2009/04/14/how-to-detect-ie8-using-javascript-client-side.aspx

Shortest way of detecting IE

More efficient way to detect any version of IE is

function isMSIE() {

return '"v' == 'v';

}


The JScript engine used in IE doesn't recognize and therefore escape vertical tabulation character while all other does.

posted on 2010-06-09 04:35 seal 阅读(429) 评论(2)  编辑  收藏 所属分类: Javascript

评论

# re: Detecting Internet Explorer More Effectively 2010-06-18 11:27 lacewigs
What a site!?!?!? You just saved me a lot of time!  回复  更多评论
  

# re: Detecting Internet Explorer More Effectively 2010-06-18 21:10 seal
It's my great pleasure! ^_^  回复  更多评论
  


只有注册用户登录后才能发表评论。


网站导航: