Setting document mode of IE based upon browser mode at run time (C hash)

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 StandardMSIE 9.0Trident/5.0
IE9 CVMSIE 7.0Trident/5.0
IE8 StandardMSIE 8.0Trident/4.0
IE8 CVMSIE 7.0Trident/4.0
IE7MSIE 7.0No Trident token
IE6MSIE 6.0No 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.

Rate This
[Total: 0 Average: 0]

1 thought on “Setting document mode of IE based upon browser mode at run time (C hash)”

Leave a Comment

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.

This site uses Akismet to reduce spam. Learn how your comment data is processed.