You are here: Reference > JavaScript > client-side > browser

Browser detection, browser related objects, properties and methods.

Browser detection:

There are several browsers in the market these days. Some of them are popular, some are not so much. Every developer would like to create web sites that work in all browsers and in different versions of them, but sometimes it's not easy to do and it is not worth the work. The optimal solution is usually to concentrate on the recent versions of the most popular browsers (Internet Explorer, Firefox, Opera, Safari and Google Chrome).
Unfortunately, the supported JavaScript interfaces, objects, methods, properties and events are often different in browsers. If you need to use a feature that is not supported by all browsers, you have two choices. You can detect the type of the user's browser or you can detect whether the required feature is supported by the user's browser. Since browsers are continuously being developed, the features supported by them often change. Therefore, if you need to use a feature that is not supported by all browsers, detect whether the required feature is supported by the user's browser instead of detecting the type of the browser. In some cases, you cannot avoid to detect the type of the user's browser (e.g. when two different browsers support the same method or property, but it works differently in them).
The following examples show solutions for feature and browser detection.
This example illustrates the use of the addEventListener and attachEvent methods. The addEventListener method is supported by Firefox, Google Chrome, Safari, Opera and Internet Explorer from version 9, the attachEvent method is supported by Internet Explorer and Opera. This solution try to use the addEventListener method first and if it is not supported, then try to use the attachEvent method.
<head>
    <script type="text/javascript">
        function OnRedClick () {
            alert ("A click event has occurred on the red button.");
        }

        function AddEventHandler () {
            var redButton = document.getElementById ("redButton");
            if (redButton.addEventListener) {   // all browsers except IE before version 9
                redButton.addEventListener ("click", OnRedClick, false);
            } 
            else {
                if (redButton.attachEvent) {    // IE before version 9
                    redButton.attachEvent ('onclick', OnRedClick);
                }
                else {
                    alert ("Your browser does not support neither the addEventListener nor the attachEvent methods.");
                }
            }
        }
    </script> 
</head>
<body onload="AddEventHandler ()">
    Click on the red button!
    <br /><br />
    <button id="redButton" style="background-color:red">Red button</button>
</body>
Did you find this example helpful? yes no
This example shows how to detect whether a property is supported by the browser. If a property is supported but its value is zero, false, null or an empty string, then the property is evaluated to false when it is used as a condition. Therefore, if you need to detect the existence of a property, use the in operator.
<head>
    <script type="text/javascript">
        function OnClick (event) {          
            if ('target' in event) {    // all browsers except IE before version 9
                var firedOn = event.target;
            }
            else {
                if ('srcElement' in event) {    // IE before version 9  
                    var firedOn = event.srcElement;
                }
                else {
                    alert ("Your browser does not support neither the srcElement nor the target properties.");
                    return;
                }
            }
            
            alert ("A click event has occurred on the " + firedOn.tagName + " element.");
        }
    </script> 
</head>
<body onclick="OnClick (event);">
    <div>Click on this text first!</div>
    <br />
    <button>Click on this button next!</button>
</body>
Did you find this example helpful? yes no
This example shows how to detect when different browsers support a property with the same name but different types. The media property of the styleSheet object works differently in Internet Explorer before version 9, than in other browsers. Fortunately, the type of the media property in Internet Explorer before version 9 differs from the type of the media property in other browsers, so the typeof operator can be used to detect the difference.
<head>
    <style id="myStyle" media="screen, print">
        body {
            font-size: 13px;
            color: #FF0000;
        }
    </style>
    
    <script type="text/javascript">
        function GetMedia () {
            var styleTag = document.getElementById ("myStyle");

                // the style sheet in the style tag
            var sheet = styleTag.sheet ? styleTag.sheet : styleTag.styleSheet;
            
            var mediaList = sheet.media;
            
            if (typeof (mediaList) == "string") {   // Internet Explorer before version 9
                alert ("The media types as a string: " + mediaList);
            }
            else {  // all browsers, except Internet Explorer before version 9
                alert ("The count of media types that belong to the style rule: " + mediaList.length);
                for (var i = 0; i < mediaList.length; i++) {
                    alert ("The " + (i+1) + ". media type: " + mediaList.item(i));
                }

                alert ("The media types as a string: " + mediaList.mediaText);
            }
        }
    </script>
</head>
<body>
    Sample text<br />
    <button onclick="GetMedia ();">Get media types</button>
</body>
Did you find this example helpful? yes no
This example shows how to detect whether a global object or an interface is supported by the browser. In these cases, you must use the typeof operator to detect their existence, because browsers that do not support the object or interface believe that it is an undeclared variable and raise an exception.
<head>
    <script type="text/javascript">
        if (typeof (HTMLAnchorElement) != "undefined") {
            HTMLAnchorElement.prototype.GetHref = function () {
                alert (this.href);
            };
        } else {
            alert ("Your browser doesn't support this example!");
        }

        function GetAnchorHref () {
            var anchor = document.getElementById ("myAnchor");
            anchor.GetHref ();
        }
    </script>
</head>
<body>
    <a id="myAnchor" href="http://www.example.com">an anchor element</a>
    <button onclick="GetAnchorHref ();">Get myAnchor href</button>
</body>
Did you find this example helpful? yes no
This example is similar to the previous one but it uses the in operator to detect whether a global object or an interface is supported by the browser. Since global objects are also accessible through the window object, the existence of a global object can be checked with the in operator on the window object.
<head>
    <script type="text/javascript">
        if ('HTMLAnchorElement' in window) {
            HTMLAnchorElement.prototype.GetHref = function () {
                alert (this.href);
            };
        } else {
            alert ("Your browser doesn't support this example!");
        }

        function GetAnchorHref () {
            var anchor = document.getElementById ("myAnchor");
            anchor.GetHref ();
        }
    </script>
</head>
<body>
    <a id="myAnchor" href="http://www.example.com">an anchor element</a>
    <button onclick="GetAnchorHref ();">Get myAnchor href</button>
</body>
Did you find this example helpful? yes no
The following examples show how to detect the type of the user's browser.
Detection of Internet Explorer:
<script type="text/javascript">
    if (navigator.appName.toLowerCase () == "microsoft internet explorer") {
        Internet Explorer specific code ...
    }
</script>
Did you find this example helpful? yes no
Another solution for detection of Internet Explorer:
<script type="text/javascript">
    var agent = navigator.userAgent.toLowerCase ();
    if (agent.search ("msie") > -1) {
        Internet Explorer specific code ...
    }
</script>
Did you find this example helpful? yes no
Detection of Firefox:
<script type="text/javascript">
    var agent = navigator.userAgent.toLowerCase ();
    if (agent.search ("firefox") > -1) {
        Firefox specific code ...
    }
</script>
Did you find this example helpful? yes no
Detection of Opera:
<script type="text/javascript">
    if (window.opera) {
        Opera specific code ...
    }
</script>
Did you find this example helpful? yes no
Another solution for detection of Opera:
<script type="text/javascript">
    var agent = navigator.userAgent.toLowerCase ();
    if (agent.search ("opera") > -1) {
        Opera specific code ...
    }
</script>
Did you find this example helpful? yes no
Detection of Safari:
<script type="text/javascript">
    var agent = navigator.userAgent.toLowerCase ();
    if (agent.search ("safari") > -1 && agent.search ("chrome") == -1) {
        Safari specific code ...
    }
</script>
Did you find this example helpful? yes no
Detection of Google Chrome:
<script type="text/javascript">
    var agent = navigator.userAgent.toLowerCase ();
    if (agent.search ("chrome") > -1 && agent.search ("safari") > -1) {
        Google Chrome specific code ...
    }
</script>
Did you find this example helpful? yes no
Finally, a complex example for browser detection. It is one of the possible solutions, there are several techniques to detect browsers.
<script type="text/javascript">
    var agent = navigator.userAgent.toLowerCase ();

    var browser = "Unknown browser";
    if (agent.search ("msie") > -1) {
        browser = "Internet Explorer";
    }
    else {
        if (agent.search ("firefox") > -1) {
            browser = "Firefox";
        } 
        else {
            if (agent.search ("opera") > -1) {
                browser = "Opera";
            } 
            else {
                if (agent.search ("safari") > -1) {
                    if (agent.search ("chrome") > -1) {
                        browser = "Google Chrome";
                    } 
                    else {
                        browser = "Safari";
                    }
                }
            }
        }
    }

    alert (browser);
</script>
Did you find this example helpful? yes no

Related objects:

General objects:
Object Support Description
clientInformation
Contains information about the browser and the operating system of the user.
clipboardData
Allows access to the data placed on the system clipboard.
Components
Implements the XPConnect (Cross Platform Connect) technology that provides interaction between XPCOM (Cross Platform Component Object Model) and JavaScript.
crypto
Represents the security object of the Firefox browser. The crypto object allows access to various browser security and cryptographic features.
external
Provides access to some additional functionalities in Internet Explorer.
history
Provides access to the browser history that contains the URLs of visited pages.
mimeType
Represents a supported MIME type.
mimeTypes
Represents a collection of all supported MIME types.
navigator
Contains information about the browser and the operating system of the user.
opera
Supports some Opera specific methods.
plugin
Contains information about an installed plug-in in the browser.
plugins
Represents a collection of all installed plugins in the browser.
screen
Contains information about the dimensions of the screen and the display settings.
sidebar
Provides methods for registering add-ons with the Firefox browser.
userProfile
9
Contains information about the current user's profile.
utils
Implements useful features for the XPConnect (Cross Platform Connect) technology.
Mozilla Bar objects:
Object Support Description
directories
Represents a bar object in Firefox, Google Chrome and Safari.
locationbar
Represents a bar object in Firefox, Google Chrome and Safari.
menubar
Represents a bar object in Firefox, Google Chrome and Safari.
personalbar
Represents a bar object in Firefox, Google Chrome and Safari.
scrollbars
Represents a bar object in Firefox, Google Chrome and Safari.
statusbar
Represents a bar object in Firefox, Google Chrome and Safari.
toolbar
Represents a bar object in Firefox, Google Chrome and Safari.

Related properties:

General browser information properties:
Property Support Description
appCodeName
(clientInformation, navigator)
Retrieves the code name of the browser.
appMinorVersion
(clientInformation, navigator)
Returns the minor version of the browser.
appName
(clientInformation, navigator)
Returns the name of the browser.
appVersion
(clientInformation, navigator)
Returns the platform and version of the browser.
buildID
(navigator)
Retrieves the build identifier of the browser.
clientInformation
(window)
Contains information about the browser and the operating system of the user.
clipboardData
(window)
Allows access to the data placed on the system clipboard.
cpuClass
(clientInformation, navigator)
Returns the central processing unit (CPU) class of the user's operating system.
enabledPlugin
(mimeType)
Returns a plugin object that contains information about the plug-in that is set to handle the data of the current MIME type.
enableSmartCardEvents
(crypto)
Sets or retrieves a Boolean value that indicates whether the document recieves SmartCard events.
onLine
(clientInformation, navigator)
Returns a Boolean value that indicates whether the browser is working online.
oscpu
(navigator)
Returns a string that contains information about the user's operating system and the central processing unit (CPU).
platform
(clientInformation, navigator)
Returns the name of the operating system platform.
product
(clientInformation, navigator)
Returns a string that contains information about the browser engine.
productSub
(clientInformation, navigator)
Returns a string that contains information about the development build number of the browser engine.
userAgent
(clientInformation, navigator)
Returns a string value that represents the user-agent header.
vendor
(clientInformation, navigator)
Returns a string that specifies the name of the browser vendor.
vendorSub
(clientInformation, navigator)
Returns a string that specifies the version number of the browser given by the vendor.
version
(crypto)
Returns a string that specifies the version number of the crypto object.
Screen and browser dimension properties:
Property Support Description
availHeight
(screen)
Returns the height of the area on the screen that is available for application windows.
availLeft
(screen)
Returns the left side of the area on the screen that is available for application windows.
availTop
(screen)
Returns the top side of the area on the screen that is available for application windows.
availWidth
(screen)
Returns the width of the area on the screen that is available for application windows.
fullScreen
(window)
3
Specifies or retrieves whether the browser application is in full-screen mode or not.
height
(screen)
Returns the vertical resolution of the display screen, in pixels.
left
(screen)
Retrieves the horizontal offset of top-left corner of the current screen relative to the top-left corner of the main screen, in pixels.
outerHeight
(window)
9
Sets or retrieves the total height of the browser window, including toolbars and scrollbars.
outerWidth
(window)
9
Sets or retrieves the total width of the browser window, including toolbars and scrollbars.
screenLeft
(window)
Returns an integer value that indicates the horizontal position of the left side of the browser's client area, relative to the left side of the screen.
screenTop
(window)
Returns an integer value that indicates the vertical position of the top side of the browser's client area, relative to the top side of the screen.
screenX
(window)
9
Returns an integer value that indicates the horizontal position of the left side of the browser window, relative to the left side of the screen.
screenY
(window)
9
Returns an integer value that indicates the vertical position of the top side of the browser window, relative to the top side of the screen.
top
(screen)
Retrieves the vertical offset of the top-left corner of the current screen relative to the top-left corner of the main screen, in pixels.
width
(screen)
Returns the horizontal resolution of the display screen, in pixels.
Display information properties:
Property Support Description
bufferDepth
(screen)
Sets or retrieves the number of bits used to represent the color of a single pixel in the off-screen bitmap buffer.
colorDepth
(screen)
Retrieves the number of bits used to represent the color of a single pixel on the screen or in the buffer when off-screen buffering is allowed.
deviceXDPI
(screen)
Returns the current number of dots per inch (DPI) of the document's viewport along the horizontal (x) axis.
deviceYDPI
(screen)
Returns the current number of dots per inch (DPI) of the document's viewport along the vertical (y) axis.
logicalXDPI
(screen)
Returns the number of dots per inch (DPI) of the document's viewport along the horizontal (x) axis at normal zoom level.
logicalYDPI
(screen)
Returns the number of dots per inch (DPI) of the document's viewport along the vertical (y) axis at normal zoom level.
pixelDepth
(screen)
9
Retrieves the number of bits used to represent the color of a single pixel on the screen or in the buffer when off-screen buffering is allowed.
systemXDPI
(screen)
8
Returns the number of dots per inch (DPI) of the display screen along the horizontal (x) axis at normal zoom level.
systemYDPI
(screen)
8
Returns the number of dots per inch (DPI) of the display screen along the horizontal (x) axis at normal zoom level.
Language properties:
Property Support Description
browserLanguage
(clientInformation, navigator)
Returns the language of the browser application or the operating system's user interface.
language
(clientInformation, navigator)
Returns the language of the browser application.
systemLanguage
(clientInformation, navigator)
Returns the language edition of the operating system.
userLanguage
(clientInformation, navigator)
Returns the current Regional and Language settings of the operating system in Internet Explorer and the language of the browser application in Opera.
MIME type properties:
Property Support Description
description
(mimeType)
Returns a long description of the current MIME type.
length
(mimeTypes)
Returns an integer that specifies the number of objects in the current collection.
plugins
(clientInformation, navigator)
Represents a collection of all installed plugins in the browser.
suffixes
(mimeType)
Returns a string value that contains a comma separated list of possible file extensions for the current MIME type.
type
(mimeType)
Returns the name of the current MIME type.
History properties:
Property Support Description
current
(history)
Returns the URL of the current document in the history array.
history
(window)
Provides access to the browser history that contains the URLs of visited pages.
length
(history)
Returns the number of entries in the history list of the current browser window.
navigationMode
(history)
Sets or retrieves the navigation type in the history.
next
(history)
Returns the URL of the next document in the history array.
previous
(history)
Returns the URL of the previous document in the history array.
Component properties:
Property Support Description
classes
(Components)
Returns a read-only object through which the registered component classes are accessible by ContractID (contract identifier).
classesByID
(Components)
Returns a read-only object through which the registered component classes are accessible by ClassID (class identifier).
interfaces
(Components)
Returns a read-only object through which interfaces are accessible by name.
interfacesByID
(Components)
Returns a read-only object through which interfaces are accessible by IID (interface identifier).
lastResult
(Components)
Returns an integer that represents the result of the most recent XPCOM method call.
manager
(Components)
Returns a reference to the global component manager service.
results
(Components)
Returns a read-only object through which the known result codes are accessible by name.
returnCode
(Components)
Returns an integer that represents the result of the current XPCOM method call.
stack
(Components)
Returns an object that represents the current JavaScript call stack.
Plugin properties:
Property Support Description
description
(plugin)
Returns the description supplied by the plugin manufacturer.
filename
(plugin)
Returns the file name of the current plugin with extension.
length
(plugin)
Returns an integer that specifies the number of associated MIME types.
length
(plugins)
Returns an integer that specifies the number of the installed plugins in the browser.
name
(plugin)
Returns the name of the plugin specified by the application manufacturer.
Additional properties:
Property Support Description
Components
(window)
Implements the XPConnect (Cross Platform Connect) technology that provides interaction between XPCOM (Cross Platform Component Object Model) and JavaScript.
cookie
(document)
Sets or retrieves the cookies stored for the current document.
cookieEnabled
(clientInformation, navigator)
Retrieves a Boolean value that indicates whether cookies are enabled in the browser.
defaultStatus
(window)
Sets or returns the default message in the status bar.
fontSmoothingEnabled
(screen)
Returns a Boolean value that indicates whether font smoothing is enabled.
frozen
(external)
Returns a Boolean value that indicates whether the document containing the current Scriptlet Component is ready to handle events.
menuArguments
(external)
Retrieves a reference to the window object that contains the context menu.
pkcs11
(window)
Retrieves a reference to the pkcs11 object. Use this object to install drivers or other software.
updateInterval
(screen)
Specifies or returns the time interval (in milliseconds) between screen updates.
utils
(Components)
Implements useful features for the XPConnect (Cross Platform Connect) technology.
visible
(locationbar, menubar, ...)
Sets or retrieves a Boolean value that indicates whether the current bar object is visible or not. This property is read-only in Google Chrome and Safari. In Firefox, the UniversalBrowserWrite privilege is required to modify the value of this property.

Related methods:

Moving and resizing the browser window:
Method Support Description
moveBy
(window)
Moves the browser window by the specified number of pixels, relative to its current coordinates.
moveTo
(window)
Moves the top-left corner of the browser window to the specified position, relative the top-left corner of the screen.
resizeBy
(window)
Resizes the browser window by the specified amount of pixels, relative to its current size.
resizeTo
(window)
Resizes the browser window to the specified size.
Navigator methods:
Method Support Description
isSupported
9
Returns whether the specified DOM module and version is supported by the current node.
javaEnabled
(clientInformation, navigator)
Returns a Boolean value that indicates whether Java is enabled in the current browser.
preference
(navigator)
Gets or sets a user preference. Only available in privileged code.
registerContentHandler
(navigator)
Allows registering a web site as a possible handler for content of the specified MIME type.
registerProtocolHandler
(navigator)
3
Allows registering a web site as a possible handler for a protocol.
taintEnabled
(clientInformation, navigator)
Returns a Boolean value that indicates whether the data-tainting security model is enabled.
ClipboardData methods:
Method Support Description
clearData
(clipboardData)
Removes the specified formatted data from the clipboard.
getData
(clipboardData)
Retrieves the specified formatted data from the clipboard.
setData
(clipboardData)
Specifies the data and its format for the clipboard.
UserProfile methods:
Method Support Description
addReadRequest
(userProfile)
9
Adds an entry to the read-requests queue.
clearRequest
(userProfile)
9
Removes all requests from the read-requests queue. Use this method after all requested data has been retrieved.
doReadRequest
(userProfile)
9
Executes all requests from the read-requests queue.
getAttribute
(userProfile)
9
Returns the value of the specified attribute from the current userProfile object.
setAttribute
(userProfile)
9
Adds an attribute with the specified name and value to the current userProfile object.
External methods:
Method Support Description
AddChannel
(external)
7
Displays a dialog box where the user has the ability to add a new channel URL, or modify the previously specified one.
AddDesktopComponent
(external)
Adds an item (image or website with location) to the Microsoft Active Desktop.
AddFavorite
(external)
Displays the 'Add a Favorite' dialog box for the specified URL and title in Internet Explorer.
addMicrosummaryGenerator
(sidebar)
Installs a microsummary generator.
addPanel
(sidebar)
Displays the 'Add Bookmark' dialog box for the specified URL and title in Firefox.
addPersistentPanel
(sidebar)
Displays the 'Add Bookmark' dialog box for the specified URL and title in Firefox.
addSearchEngine
(sidebar)
Installs a Sherlock formatted search engine plugin into the browser application.
AddSearchProvider
(external, sidebar)
7
Installs a search engine plugin into the browser application.
AutoCompleteSaveForm
(external)
Stores the values and names of the named input:password and input:text elements in the specified form for autocompletion.
AutoScan
(external)
7
Attempts to find a Web site based on the specified domain part.
IsSearchProviderInstalled
(external, sidebar)
7
Returns an integer that represents whether the specified search provider is installed and whether it is the default.
IsSubscribed
(external)
Returns whether the client is subscribed to the specified channel.
NavigateAndFind
(external)
Loads the document at the specified URL into the current window and selects the specified text.
ShowBrowserUI
(external)
Opens the specified system dialog.
Opera object methods:
Method Support Description
buildNumber
(opera)
Returns the build number of the browser in Opera.
collect
(opera)
Tries to initiate the JavaScript garbage collection.
postError
(opera)
Prints each argument as a separate message to the Error Console.
version
(opera)
Returns the version number of the browser in Opera.
Utility methods:
Method Support Description
evalInSandbox
(utils)
Executes a piece of JavaScript code in a Sandbox object.
forceGC
(utils)
Allows to force a garbage collection (automatic memory management) cycle.
getWeakReference
(utils)
Returns an instance of the nsIWeakReference interface.
import
(utils)
Includes a JavaScript code module into the current script. You can define a scope for the contents of the imported file.
reportError
(utils)
Reports an error to the Error Console.
Sandbox
(utils)
Creates a Sandbox object that can be used as an executing environment for the evalInSandbox method.
History methods:
Method Support Description
back
(history, window)
Loads the previous page form the history list into the current window.
forward
(history, window)
Loads the next page form the history list into the current window.
go
(history)
Loads a page from the history list into the current window.
Component methods:
Method Support Description
Constructor
(Components)
Creates a function that can be used to create an instance of the specified XPCOM component.
Exception
(Components)
Creates an XPCOM exception object that provides more complex error handling in JavaScript.
ID
(Components)
Creates an object that represents an IID (interface identifier).
isSuccessCode
(Components)
Returns a Boolean value that indicates whether the specified XPCOM result code is valid or not.
Plugin methods:
Method Support Description
item
(plugin)
Returns a mimeType object that represents an associated MIME type, by index.
item
(plugins)
Returns a plugin object from the current collection by position.
namedItem
(plugin)
Returns a mimeType object that represents an associated MIME type, by name.
namedItem
(plugins)
Returns a plugin object from the current collection by name.
refresh
(plugins)
Refreshes the plugins collection to make the newly installed plugins available.
Cryptographic methods:
Method Support Description
alert
(crypto)
3.5
Displays an alert window with the specified message and an OK button. The support for this method has been removed in Firefox 3.5.
disableRightClick
(crypto)
Disables the right mouse click. Not Implemented yet.
generateCRMFRequest
(crypto)
Generates a CRMF (Certificate Request Message Format) request.
importUserCertificates
(crypto)
Imports a certificate for the user.
logout
(crypto)
Logs the user out.
popChallengeResponse
(crypto)
random
(crypto)
Generates a random number. Not implemented yet.
User Contributed Comments

Post Content

Post Content