YUI 3.x Home -

YUI Library Examples: The YUI Global Object: Browser Detection with UA

Note: This is YUI 3.x. Looking for YUI 2.x?

The YUI Global Object: Browser Detection with UA

This example demonstrates the use of UA to identify the user's browser and to branch JavaScript logic based on what browser is being used. (Note: We strongly recommend using feature detection rather than user-agent sniffing to fork code; only use this technique where it is absolutely necessary to do so — for example, in cases where browsers do not report their own capabilities accurately.)

UA properties set for your browser:

First, a word of caution

Please DO NOT use this in place of feature detection. Though many browsers have known JavaScript implementation quirks, it is bad practice and unsafe coding to make the assumption that because the page is being viewed in browser X that you can rely on feature Y being available. Check for feature Y if you need it.

Browser sniffing is an imprecise science, and relies on many things in the browser environment to be just right. Though many techniques are very accurate, 100% accuracy can't be guaranteed.

Use the UA object to inform you of what browser your page is being viewed in, but avoid using this technique unless feature detection will not serve your purpose.

What UA looks like

UA is an object literal containing keys for most major user agents. The key corresponding to the current browser is assigned a version number. All others have value 0, with the exception of the mobile property, which is a string value indicating the name of a supported mobile device that was detected or null.

There's more information on the UA object and value ranges in the API Documentation.

Instantiate YUI

User Agent Info

In this simple example, we use the each to iterate the UA object.

Copyright © 2009 Yahoo! Inc. All rights reserved.

Privacy Policy - Terms of Service - Copyright Policy - Job Openings