Подтвердить что ты не робот

Как обнаружить браузер с угловым?

Мне нужно определить, является ли браузер IE или Edge с Angular (TypeScript). Является ли это возможным? Если да, то как?

4b9b3361

Ответ 1

Я использовал это раньше, и это работало хорошо.

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

Ответ 2

Пожалуйста, используйте следующий код:

// 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 = /*@[email protected]*/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;

Ответ 3

Для угловых пользователей, вы можете использовать этот модуль npm install ngx-device-detector --save

Выше ответы не работают для меня

Ответ 4

Если вы хотите показывать сообщение, когда браузер обнаруживает IE (5,6,7,8), тогда вы можете использовать строку кода.

Во-первых, этот код используется только в файле index.html, так как компилятор сначала читает этот файл.

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

Ответ 5

Вы можете использовать регулярное выражение с useragent для обнаружения IE.

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

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

    return isIE;
}

но всегда рекомендуется использовать обнаружение функций вместо обнаружения браузера. Вы можете использовать библиотеку modernizr для этого https://modernizr.com

Ответ 6

Это сработало для меня:

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

}

После того как вы вызвали getBrowserName(), вы можете сравнить возвращаемое значение с ==='edge', чтобы увидеть, работаете ли вы в граничном браузере.

Ответ 7

если вы довольны использованием внешнего модуля, вы можете использовать детектор ngx-device.

$ npm install ngx-device-detector --save

Использование:

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

В вашем компоненте, где вы хотите использовать службу устройств

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

Сервис устройства Содержит следующие свойства

  1. браузер
  2. ОС
  3. устройство
  4. UserAgent
  5. os_version

Вспомогательные методы

isMobile(): возвращает, если устройство является мобильным устройством (android/iPhone/windows-phone и т.д.)

isTablet(): возвращает, если устройство использует планшет (iPad и т.д.)

isDesktop(): возвращает, если приложение работает в браузере рабочего стола

Вот ссылка Документы: https://koderlabs.github.io/ngx-device-detector/index.html