简体   繁体   中英

How do I capture the browser being used to access a webpage?

Let's say I am writing a simple web page containing two boxes, name and pet name . If an end-user were to browse to this site with any given web browser, how would I make a pop-up notification appear that displays the user's browser?

For example, if I browse to this page using Microsoft Edge or IE 11, how would I immediately have a dialogue box appear that states something along the lines of:

"You are using IE11" or "You are using Microsoft Edge"?

Closest thing youre going to get to what you want is going through the browsers "User Agent String" in the frontend.

similar : Getting the User Agent with JavaScript

Here is also a library that can pass the value into a more usable state. https://github.com/faisalman/ua-parser-js

There are many other well documented Stack Overflow questions on how to detect browser version: How can you detect the version of a browser?

Once you have the browser version, instead of using a console log as in the accepted answer above, an alert would do the trick of showing a dialog box with that information.


Update: Further down the page I linked is browser detection that works on Edge and IE. Credit to Brandon

navigator.browserSpecs = (function(){
    var ua = navigator.userAgent, tem, 
        M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
    if(/trident/i.test(M[1])){
        tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
        return {name:'IE',version:(tem[1] || '')};
    }
    if(M[1]=== 'Chrome'){
        tem = ua.match(/\b(OPR|Edge)\/(\d+)/);
        if(tem != null) return {name:tem[1].replace('OPR', 'Opera'),version:tem[2]};
    }
    M = M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
    if((tem = ua.match(/version\/(\d+)/i))!= null)
        M.splice(1, 1, tem[1]);
    return {name:M[0], version:M[1]};
})();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM