Home >Web Front-end >JS Tutorial >How Can I Detect Internet Explorer and Edge Browser Usage in JavaScript?

How Can I Detect Internet Explorer and Edge Browser Usage in JavaScript?

DDD
DDDOriginal
2024-12-01 06:09:221006browse

How Can I Detect Internet Explorer and Edge Browser Usage in JavaScript?

Identifying Internet Explorer Usage

In an effort to control function execution specifically within Internet Explorer (IE), you may encounter a query regarding how to verify user's browser compatibility prior to initiating the function. This becomes particularly important when targeting users who consistently utilize IE8 or later versions.

Determining Browser Usage

While ascertaining the specific browser utilized by a user may be desirable, it is not mandatory. One straightforward method for verifying IE usage is by checking for the presence of window.document.documentMode. If this property exists, IE is being employed.

Sample Code Utilizing window.document.documentMode:

if (window.document.documentMode) {
  // Do IE stuff
}

User Agent String in Edge

Edge, a contemporary browser, employs Chromium as its rendering engine, resulting in altered User Agent String values. The method detailed below effectively detects IE and Edge variants:

Function for Detecting IE/Edge (detectIEEdge):

function detectIEEdge() {
    var ua = window.navigator.userAgent;

    var msie = ua.indexOf('MSIE ');
    if (msie > 0) {
        // IE 10 or older
        return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
    }

    var trident = ua.indexOf('Trident/');
    if (trident > 0) {
        // IE 11
        var rv = ua.indexOf('rv:');
        return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
    }

    var edge = ua.indexOf('Edge/');
    if (edge > 0) {
       // Edge
       return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
    }

    // Other browser
    return false;
}

Example Usage:

alert('IEEdge ' + detectIEEdge());

The above is the detailed content of How Can I Detect Internet Explorer and Edge Browser Usage in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn