How to detect browser with Angular?

AngularTypescriptBrowser Detection

Angular Problem Overview


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

Angular Solutions


Solution 1 - Angular

I have used this before and it worked well.

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

Solution 2 - Angular

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 - Angular

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 - Angular

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 - Angular

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

Above answers din't work for me

Solution 6 - Angular

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.
    }
}

Solution 7 - Angular

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

Solution 8 - Angular

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

Solution 9 - Angular

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');

Solution 10 - Angular

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

const isChromiumBased =
  !!window["chrome"] &&
  (!!window["chrome"]["webstore"] || !!window["chrome"]["runtime"]);

Solution 11 - Angular

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>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLiutasView Question on Stackoverflow
Solution 1 - AngularargooView Answer on Stackoverflow
Solution 2 - AngularI. AhmedView Answer on Stackoverflow
Solution 3 - AngularScopperloitView Answer on Stackoverflow
Solution 4 - AngulartroYmanView Answer on Stackoverflow
Solution 5 - AngularpenduDevView Answer on Stackoverflow
Solution 6 - AngularShayaView Answer on Stackoverflow
Solution 7 - AngularSam Mirza GharchehView Answer on Stackoverflow
Solution 8 - AngularAmit GaikwadView Answer on Stackoverflow
Solution 9 - AngularAkash RaviView Answer on Stackoverflow
Solution 10 - AngularsurajmallView Answer on Stackoverflow
Solution 11 - Angularnagender pratap chauhanView Answer on Stackoverflow