import { Inject, Injectable, } from '@angular/core'; import { BrowserTypesEnum } from './browser-types.enum'; import { BrowserDetailsInterface, BrowserDetectionPatternsInterface, } from './../../../models/index'; @Injectable() export class BrowserDetectorService { private _browserType: BrowserTypesEnum; private _userAgentPatterns: BrowserDetectionPatternsInterface[] = [ { name: 'Chrome', pattern: /Chrome\/([0-9\.]+)\s/, }, { name: 'Edge', pattern: /Edge\/([0-9\.]+)$/, }, { name: 'Firefox', pattern: /Firefox\/([0-9\.]+)$/, }, { name: 'IE', pattern: /MSIE\s([0-9\.]+).|Trident.+rv:([0-9\.]+)./, }, { name: 'Safari', pattern: /[^Chrome]\/([0-9\.]+)\sSafari/, }, { name: 'IOS', pattern: /iPad|iPhone|iPod/, }, ]; constructor( @Inject('window') private _window: Window, ) { this._browserType = this._getBrowserType(); } public isFirefox() { return this._browserType === BrowserTypesEnum.Firefox; } public isSafari() { return this._browserType === BrowserTypesEnum.Safari; } public isChrome() { return this._browserType === BrowserTypesEnum.Chrome; } public getBrowserDetails(): BrowserDetailsInterface { const userAgent = this._window.navigator.userAgent; const patterns = this._userAgentPatterns; const browser: BrowserDetailsInterface = { name: 'unknown', version: 'unknown', }; for (let i = this._userAgentPatterns.length; i--;) { const match = userAgent.match(patterns[i].pattern); if (match && match.length > 0) { browser.name = patterns[i].name; browser.version = match[2] || match[1]; break; } } return browser; } public isIE() { return this.getBrowserDetails().name === 'IE'; } public isIOS() { return this.getBrowserDetails().name === 'IOS'; } private _getBrowserType() { const nativeWindow = this._window; if (nativeWindow.navigator.userAgent .match(/Firefox/) ) { return BrowserTypesEnum.Firefox; } else if ( nativeWindow.navigator.userAgent.match(/Safari/) && !nativeWindow.navigator.userAgent.match(/Chrome/) ) { return BrowserTypesEnum.Safari; } return BrowserTypesEnum.Chrome; } }