68

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

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Liutas
  • 5,547
  • 4
  • 23
  • 22

11 Answers11

82

I have used this before and it worked well.

const isIEOrEdge = /msie\s|trident\/|edge\//i.test(window.navigator.userAgent)
argoo
  • 1,428
  • 12
  • 17
  • @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 – Maddy Nov 19 '18 at 15:15
  • @Maddy You can use it in a component, service etc. – argoo Nov 24 '18 at 19:55
  • 2
    I don't think you need to use `let` here, `const` should be more appropriate. – Okonomiyaki3000 May 13 '19 at 04:54
  • 1
    Nice ... works also for Edge2 (negative result as was supposed), thank you – Václav Švára Feb 18 '20 at 19:53
  • 1
    For detecting FF also I used -> isIEOrEdgeOrFF: boolean = /msie\s|Firefox|trident\/|edge\//i.test(window.navigator.userAgent); – Hamid Reza Apr 06 '20 at 09:54
  • 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 Dec 02 '21 at 14:42
  • Please note this from _developer.mozilla.org_ : [Browser detection using the user agent](https://developer.mozilla.org/en-US/docs/Web/HTTP/Browser_detection_using_the_user_agent) – Guillaume Husta Aug 11 '22 at 08:56
35

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;
I. Ahmed
  • 2,438
  • 1
  • 12
  • 29
  • 2
    @Liutas Angular is using Typescript. And it is a superset of JavaScript. Of course you can. – Roland Rácz Jan 10 '18 at 08:29
  • 5
    angular cli throws an error using window,chrome, but it works using `!!window['chrome']&& !!window['chrome']['webstore']` – Cristian Sepulveda Jun 20 '18 at 05:44
  • 2
    this code shows me false for all of the browsers now.. Launching it from Chrome on Win7 – grreeenn Dec 19 '18 at 16:20
  • Have you tried with !!window['chrome']&& !!window['chrome']['webstore'] – I. Ahmed Dec 20 '18 at 00:43
  • `chrome.webstore` is undefined in recent version. Use `!!window.chrome && (!!window.chrome.webstore || !!window.chrome.runtime);` instead – devqon Jan 08 '19 at 11:58
  • @RolandRácz your comment add no value to the question. Liutas had a good point, the code does not work in angular without modification – skydev Aug 30 '19 at 12:40
  • @skydev It's tested code and it worked perfectly in Angular – I. Ahmed Sep 03 '19 at 02:39
  • 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! – Simon_Weaver Sep 18 '19 at 19:38
  • 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. – Marcel Jun 01 '22 at 06:16
28

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

Scopperloit
  • 920
  • 12
  • 23
  • 1
    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 Dec 02 '21 at 14:31
  • 4
    @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. – Scopperloit Dec 02 '21 at 23:06
20

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.

msanford
  • 11,803
  • 11
  • 66
  • 93
troYman
  • 1,648
  • 16
  • 18
  • 1
    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? – Malhaar Punjabi Mar 02 '20 at 21:28
  • This does not return chrome on an iPhone 12, using chrome ... – Stefan Walther Jun 09 '20 at 17:37
  • Add `case agent.indexOf('edg') > -1: return 'edge';` – James Parker Dec 02 '21 at 14:43
  • 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 – whallz Feb 02 '22 at 18:52
8

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

Above answers din't work for me

penduDev
  • 4,743
  • 35
  • 37
  • 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. – Nagender Pratap Chauhan Jul 01 '19 at 06:56
  • @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 – penduDev Jul 07 '19 at 15:53
  • 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":"Unknown","os_version":"windows-10","browser_version":"75.0.3770.100"}`. Plus, it's the angular way! – BobC Jul 13 '19 at 23:14
  • 1
    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="" . – egalot Nov 01 '19 at 19:24
4

Browsers userAgent tend to differ and evolve over time. Instead of manually parsing the userAgent, consider using a well-maintained library that ensures future support. The most popular options are:

1. UAParser.js

This excellent library will analyze the client browser, engine, OS, CPU, and Device type/model from User-Agent data with a relatively small footprint. It's highly maintained and extremely popular (7.3M weekly downloads ATTOW). Usage is easy:

import { UAParser } from 'ua-parser-js'; 

const parser = new UAParser();
const result = parser.getResult();

const isEdge = result.browser == 'Edge';

2. Angular Material

The "Platform" detection module was introduced in Angular Material V6.4.7:

Platform: service to detect the current platform by comparing the userAgent strings and checking browser-specific global properties.

Important note on EDGE detection: Since version 79 EDGE uses the Blink browser engine, so this option works only for old EDGE versions.

Import the Platform service and check directly for EDGE (or any other browser / OS):

import { Platform } from '@angular/cdk/platform';

@Injectable()
export class AppService {
    
    isEdge: boolean;

    constructor(private platform: Platform) {
        this.isEdge = this.platform.EDGE; // or IOS, SAFARI, ANDROID, etc.
    }
}
Shaya
  • 2,792
  • 3
  • 26
  • 35
  • 1
    This should be the right answer, parsing the userAgent string is just asking for maintenance issues over time. – RocketMan Feb 16 '21 at 18:05
  • 1
    Platform doesn't work that well - tested on edge and platform.EDGE came back as false. UAParser works well tho! – Karen Oct 05 '21 at 07:37
  • Many thanks, @Karen. This is very important to know. – Shaya Oct 06 '21 at 09:13
  • 1
    This article explains the different Platform booleans very well: https://www.decodedfrontend.io/detect-browser-and-os-with-angular-cdk-platform-module/ – Stephanie Feb 18 '22 at 10:30
  • 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." – Shaya Feb 19 '22 at 11:14
3

if you are happy with using the external module , you can use the ngx-device-detector.

$ npm install ngx-device-detector --save

Usage :

  import { NgModule } from '@angular/core';
  import { DeviceDetectorModule } from 'ngx-device-detector';
  ...
  @NgModule({
    declarations: [
      ...
      LoginComponent,
      SignupComponent
      ...
    ],
    imports: [
      CommonModule,
      FormsModule,
      DeviceDetectorModule.forRoot()
    ],
    providers:[
      AuthService
    ]
    ...
  })

In your component where you want to use the Device Service

 import { Component } from '@angular/core';
  ...
  import { DeviceDetectorService } from 'ngx-device-detector';
  ...
  @Component({
    selector: 'home',  // <home></home>
    styleUrls: [ './home.component.scss' ],
    templateUrl: './home.component.html',
    ...
  })

  export class HomeComponent {
    deviceInfo = null;
    ...
    constructor(..., private http: Http, private deviceService: DeviceDetectorService) {
      this.epicFunction();
    }
    ...
    epicFunction() {
      console.log('hello `Home` component');
      this.deviceInfo = this.deviceService.getDeviceInfo();
      const isMobile = this.deviceService.isMobile();
      const isTablet = this.deviceService.isTablet();
      const isDesktopDevice = this.deviceService.isDesktop();
      console.log(this.deviceInfo);
      console.log(isMobile);  // returns if the device is a mobile device (android / iPhone / windows-phone etc)
      console.log(isTablet);  // returns if the device us a tablet (iPad etc)
      console.log(isDesktopDevice); // returns if the app is running on a Desktop browser.
    }
    ...
  }

Device service Holds the following properties

  1. browser
  2. os
  3. device
  4. userAgent
  5. os_version

Helper Methods

isMobile() : returns if the device is a mobile device (android / iPhone/ windows-phone etc)

isTablet() : returns if the device us a tablet (iPad etc)

isDesktop() : returns if the app is running on a Desktop browser

Here is the Documents link: https://koderlabs.github.io/ngx-device-detector/index.html

1

You can use regex with useragent for detecting IE.

 private isIE() {
    const match = navigator.userAgent.search(/(?:Edge|MSIE|Trident\/.*; rv:)/);
    let isIE = false;

    if (match !== -1) {
        isIE = true;
    }

    return isIE;
}

but, Its always recommended to use feature detection instead of browser detection. You can use modernizr library for that https://modernizr.com

Amit Gaikwad
  • 923
  • 1
  • 9
  • 15
1

You can get the browser name using the following code :

let match = navigator.userAgent.search(/(?:Edge|MSIE|Trident\/.*; rv:)/);
let isIE = false;

if (match !== -1) {
    isIE = true;
}
console.log(isIE,'isIE');
KristofMols
  • 3,487
  • 2
  • 38
  • 48
Akash Ravi
  • 19
  • 1
1

To detect if the browser is based on Chromium, use the following code:

const isChromiumBased =
  !!window["chrome"] &&
  (!!window["chrome"]["webstore"] || !!window["chrome"]["runtime"]);
grooveplex
  • 2,492
  • 4
  • 28
  • 30
surajmall
  • 178
  • 1
  • 7
  • `!!(window.chrome && (window.chrome.webstore || window.chrome.runtime))` – MrHIDEn Aug 13 '20 at 09:52
  • 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 !!! – Mike Gledhill Jun 29 '21 at 11:55
0

If you want to show message when browser detect IE(5,6,7,8) then you can used line of code.

Firstly this code used only in index.html file becasue compiler firstly read this file.

<body>
<p id="NRL" style="background-color: aquamarine;text-align: center"></p>
<app-root></app-root>

<script>

  let isIE1 =/^.*MSIE [5-9]/i.test(window.navigator.userAgent);
    if(isIE1){
      alert('you are using older version of IE .........')

      document.getElementById("NRL").innerHTML = "you are using older version of IE .........";
    }
  </script>
</body>