Recently I was working on a project that required me to force the user into IE9 document mode, but ONLY if they were using IE9 compatibility view (CV) or IE 10 mode.
The main elements that we need to look at are the Version token and the Trident token. Below are the tokens that you will find in each browser:
VERSION TRIDENT
IE9 Standard | MSIE 9.0 | Trident/5.0 |
IE9 CV | MSIE 7.0 | Trident/5.0 |
IE8 Standard | MSIE 8.0 | Trident/4.0 |
IE8 CV | MSIE 7.0 | Trident/4.0 |
IE7 | MSIE 7.0 | No Trident token |
IE6 | MSIE 6.0 | No Trident token |
As you can see, each browser has a unique combination of these two tokens. We can use this knowledge to now create a function that will tell us what browser mode is in use. My function is shown below:
private string GetIEBrowserMode() { string mode = ""; string userAgent = Request.UserAgent; //entire UA string string browser = Request.Browser.Type; //Browser name and Major Version # if (userAgent.Contains("Trident/5.0")) //IE9 has this token { if (browser == "IE7") { mode = "IE9 Compatibility View"; } else { mode = "IE9 Standard"; } } else if (userAgent.Contains("Trident/4.0")) //IE8 has this token { if (browser == "IE7") { mode = "IE8 Compatibility View"; } else { mode = "IE8 Standard"; } } else if (!userAgent.Contains("Trident")) //Earlier versions of IE do not contain the Trident token { mode = browser; } return mode; } protected void Page_Load(object sender, EventArgs e) { if (GetIEBrowserMode() == "IE9 Compatibility View") { HtmlMeta force = new HtmlMeta(); force.HttpEquiv = "X-UA-Compatible"; force.Content = "IE=8"; Header.Controls.AddAt(0, force); } }
This snippet is very straightforward. We are creating a new meta tag with the necessary attributes, and we are adding it to the header of our page at an index of 0 because it needs to be among the first header elements. Now run your page! If you’d like to test the results, a good way to do so is to open IE Developer Tools (F12) and at the top there will be a drop down titled “Browser Mode”. Add a label to your page that shows the result of GetIEBrowserMode() and you can easily switch between the different browser modes with an accurate detection.
good article.. keep it up.. Smile