How to detect browser with Angular?

113,279

Solution 1

I have used this before and it worked well.

const isIEOrEdge = /msie\s|trident\/|edge\//i.test(window.navigator.userAgent)

Solution 2

Please use the following code:

// Opera 8.0+
    var isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;

    // Firefox 1.0+
    var isFirefox = typeof InstallTrigger !== 'undefined';

    // Safari 3.0+ "[object HTMLElementConstructor]" 
    var isSafari = /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || safari.pushNotification);

    // Internet Explorer 6-11
    var isIE = /*@cc_on!@*/false || !!document.documentMode;

    // Edge 20+
    var isEdge = !isIE && !!window.StyleMedia;

    // Chrome 1+
    //var isChrome = !!window.chrome && !!window.chrome.webstore;
    // If isChrome is undefined, then use:
    var isChrome = !!window.chrome && (!!window.chrome.webstore || !!window.chrome.runtime);
    // Blink engine detection
    var isBlink = (isChrome || isOpera) && !!window.CSS;

    var output = 'Detecting browsers by ducktyping:<hr>';
    output += 'isFirefox: ' + isFirefox + '<br>';
    output += 'isChrome: ' + isChrome + '<br>';
    output += 'isSafari: ' + isSafari + '<br>';
    output += 'isOpera: ' + isOpera + '<br>';
    output += 'isIE: ' + isIE + '<br>';
    output += 'isEdge: ' + isEdge + '<br>';
    output += 'isBlink: ' + isBlink + '<br>';
    document.body.innerHTML = output;

Solution 3

For people still finding this thread:

If you're on Angular 10 or above, I suggest using the PlatformModule, which was added to the Angular Material CDK in version 10.

https://material.angular.io/cdk/platform/api

Solution 4

This worked for me:

  public getBrowserName() {
    const agent = window.navigator.userAgent.toLowerCase()
    switch (true) {
      case agent.indexOf('edge') > -1:
        return 'edge';
      case agent.indexOf('opr') > -1 && !!(<any>window).opr:
        return 'opera';
      case agent.indexOf('chrome') > -1 && !!(<any>window).chrome:
        return 'chrome';
      case agent.indexOf('trident') > -1:
        return 'ie';
      case agent.indexOf('firefox') > -1:
        return 'firefox';
      case agent.indexOf('safari') > -1:
        return 'safari';
      default:
        return 'other';
    }
}

After you called getBrowserName() you can compare the return value with ==='edge' to see if you are operating in the edge browser.

Solution 5

For angular users, you can use this module npm install ngx-device-detector --save

Above answers din't work for me

Share:
113,279
Liutas
Author by

Liutas

Updated on July 08, 2022

Comments

  • Liutas
    Liutas almost 2 years

    I need to detect if browser is IE or Edge with Angular (TypeScript). Is it possible? If so, how?

  • Roland Rácz
    Roland Rácz over 6 years
    @Liutas Angular is using Typescript. And it is a superset of JavaScript. Of course you can.
  • Cristian Sepulveda
    Cristian Sepulveda about 6 years
    angular cli throws an error using window,chrome, but it works using !!window['chrome']&& !!window['chrome']['webstore']
  • Maddy
    Maddy over 5 years
    @aargoo, i am new to angularjs. Can you tell me where do I use this code? I understand the config > run > controller order of call but where does this code go. Thanks
  • argoo
    argoo over 5 years
    @Maddy You can use it in a component, service etc.
  • grreeenn
    grreeenn over 5 years
    this code shows me false for all of the browsers now.. Launching it from Chrome on Win7
  • I. Ahmed
    I. Ahmed over 5 years
    Have you tried with !!window['chrome']&& !!window['chrome']['webstore']
  • devqon
    devqon over 5 years
    chrome.webstore is undefined in recent version. Use !!window.chrome && (!!window.chrome.webstore || !!window.chrome.runtime); instead
  • Okonomiyaki3000
    Okonomiyaki3000 about 5 years
    I don't think you need to use let here, const should be more appropriate.
  • Nagender Pratap Chauhan
    Nagender Pratap Chauhan about 5 years
    modules always increase bundle size so that I think why should we used third-party modules whereas we create own code so this is bed approach.
  • penduDev
    penduDev almost 5 years
    @nagenderpratapchauhan yes thats true, for me it was a matter of using a utility as I could not spend a 4-5 hours on writing & testing my custom browser detector. I believe that this module also have just the required code and a lot of extra as there is a very specific function that this module performs
  • BobC
    BobC almost 5 years
    Took 5 minutes from install to successful deployment. deviceInfo: {"userAgent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36","os":"Windows","browser":"Chrome","device":"U‌​nknown","os_version"‌​:"windows-10","brows‌​er_version":"75.0.37‌​70.100"}. Plus, it's the angular way!
  • skydev
    skydev almost 5 years
    @RolandRácz your comment add no value to the question. Liutas had a good point, the code does not work in angular without modification
  • I. Ahmed
    I. Ahmed almost 5 years
    @skydev It's tested code and it worked perfectly in Angular
  • aruno
    aruno almost 5 years
    It depends what you want to do with it this knowledge in Angular!! This is just Javascript. If you want to block your entire site and show a popup (as I did) then put this in ngOnInit and set a boolean hideSite == true then put *ngIf="!hideSite" on your router-outlet in app.component.ts. If you want to do anything else that's kind of out of scope without more detailed requirements!
  • egalot
    egalot over 4 years
    This was working for a better part of a year, but at some point (perhaps when updating to angular 8) it stopped working. Note, it works perfectly in development (ng serve) but fails with the production build. It simply returns: browser="" .
  • Václav Švára
    Václav Švára over 4 years
    Nice ... works also for Edge2 (negative result as was supposed), thank you
  • Malhaar Punjabi
    Malhaar Punjabi over 4 years
    bit confusing. When I run your code this on Chrome, it prints const agent = window.navigator.userAgent.toLocaleLowerCase(); console.log('agent' + agent); agentmozilla/5.0 (windows nt 10.0; win64; x64) applewebkit/537.36 (khtml, like gecko) chrome/70.0.3538.102 safari/537.36 And on Edge: agentmozilla/5.0 (windows nt 10.0; win64; x64) applewebkit/537.36 (khtml, like gecko) chrome/70.0.3538.102 safari/537.36 edge/18.18362 (agent.indexOf('safari') > -1 or (agent.indexOf('chrome') > -1 will always return true on any browser. Can you please clarify this?
  • Hamid Reza
    Hamid Reza about 4 years
    For detecting FF also I used -> isIEOrEdgeOrFF: boolean = /msie\s|Firefox|trident\/|edge\//i.test(window.navigator.use‌​rAgent);
  • Stefan Walther
    Stefan Walther about 4 years
    This does not return chrome on an iPhone 12, using chrome ...
  • MrHIDEn
    MrHIDEn almost 4 years
    !!(window.chrome && (window.chrome.webstore || window.chrome.runtime))
  • RocketMan
    RocketMan over 3 years
    This should be the right answer, parsing the userAgent string is just asking for maintenance issues over time.
  • Mike Gledhill
    Mike Gledhill about 3 years
    I tried this... and right now, this line of code works perfectly on my deployed version of my Angular app, but (in the Chrome tab right next to it) those same lines of code say it's not Chrome, in my localhost version. Aggggghhh !!!
  • Karen
    Karen over 2 years
    Platform doesn't work that well - tested on edge and platform.EDGE came back as false. UAParser works well tho!
  • Shaya
    Shaya over 2 years
    Many thanks, @Karen. This is very important to know.
  • James Parker
    James Parker over 2 years
    This doesn't work very well. I'm currently looking at the result returned from this in Edge and it's saying EDGE:false
  • James Parker
    James Parker over 2 years
    This is no longer valid. The user agent value returned for edge is mozilla/5.0 (windows nt 10.0; win64; x64) applewebkit/537.36 (khtml, like gecko) chrome/96.0.4664.55 safari/537.36 edg/96.0.1054.41
  • James Parker
    James Parker over 2 years
    Add case agent.indexOf('edg') > -1: return 'edge';
  • James Parker
    James Parker over 2 years
    add edg to the regex search.
  • Scopperloit
    Scopperloit over 2 years
    @JamesParker That's because you're using the new Edge browser which is actually Chromium based. If you instead check for Blink, it will probably return true. Blink is the browser layout engine and part of Chromium, so this will be true for both Edge and Chrome. I believe the EDGE: false is looking for the old Microsoft Edge browser, which is not Chromium based.
  • agbb
    agbb over 2 years
    just a note: this snippet depends heavily on browser usage metrics, if you just test for agent.indexOf('safari') > -1 it would evaluate to true on almost every modern browser, since most browsers repeat parts of their user-agent strings, so this detection here relies on the order the evaluations are made
  • Stephanie
    Stephanie over 2 years
    This article explains the different Platform booleans very well: decodedfrontend.io/…
  • Shaya
    Shaya over 2 years
    Hey @Stephanie, thanks. Quoting this article: "Note! Since version 79 EDGE uses the Blink browser engine, so this option works only for old EDGE versions."
  • Marcel
    Marcel about 2 years
    It does not work with my app on angular 12. window.chrome.runtime does not exist in the browser tab of my angular app, in other tabs it exists.