Detect Browser Version And Name In Angular

In this article we will learn about how to detect the browser version and name in angular.

Write following code in app.component.html :

<div class="container mt-5">

  <h2>Display Browser Name and Version</h2>

  <table class="table table-striped mt-3 w-25">
    <thead>
      <tr>
        <th>Browser Name</th>
        <th>Browser Version</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>{{ browserName | titlecase }}</td>
        <td>{{ browserVersion | titlecase }}</td>
      </tr>
    </tbody>
  </table>
</div>

Write following code in app.component.ts :

import { Component, OnInit } from '@angular/core'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {

  browserName = '';
  browserVersion = '';

  ngOnInit() {
    this.browserName = this.BrowserName();
    this.browserVersion = this.BrowserVersion();
  }

  BrowserName() {
    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';
    }
  }

  BrowserVersion() {
    var userAgent = navigator.userAgent, tem,
      matchTest = userAgent.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];

    if (/trident/i.test(matchTest[1])) {
      tem = /\brv[ :]+(\d+)/g.exec(userAgent) || [];
      return 'IE ' + (tem[1] || '');
    }
    if (matchTest[1] === 'Chrome') {
      tem = userAgent.match(/\b(OPR|Edge)\/(\d+)/);
      if (tem != null) return tem.slice(1).join(' ').replace('OPR', 'Opera');
    }
    matchTest = matchTest[2] ? [matchTest[1], matchTest[2]] : [navigator.appName, navigator.appVersion, '-?'];
    if ((tem = userAgent.match(/version\/(\d+)/i)) != null) matchTest.splice(1, 1, tem[1]);
    return matchTest.join(' ');
  }

}

Now run angular project using ng serve

Output :

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories