How to stop execution of angular and show a message to Intenet Explorer users?

问题: I have an angular 7 project, I want to show IE users a message like this: Your browser is outdated please use chrome or firefox!. I can detect the browser by following c...

问题:

I have an angular 7 project, I want to show IE users a message like this: Your browser is outdated please use chrome or firefox!.

I can detect the browser by following code:

       var browser = (function(agent){
          switch(true){
            case agent.indexOf("edge") > -1: return "edge";
            case agent.indexOf("opr") > -1 && !!window.opr: return "opera";
            case agent.indexOf("chrome") > -1 && !!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";
          }
        })(window.navigator.userAgent.toLowerCase());
        console.log(browser)

        if(browser === 'ie'){
          alert("IE detected!"); 
        }

This script is placed in the index.html file under <app-root></app-root> element. Now how to stop angular from parsing <app-root> and show a message in the document body?


回答1:

You can apply your logic within main.ts. This is the starting file of an angular app and you can prevent angular from bootstrapping. Take a look at this blitz

First I put a piece of HTML into index.html

<div id="ie-message" style="display: none">This is IE message</div>

Next, I just copied your code into main.ts

var browser = (function(agent){
  switch(true){
    case agent.indexOf("edge") > -1: return "edge";
    case agent.indexOf("opr") > -1 && !!window.opr: return "opera";
    case agent.indexOf("chrome") > -1 && !!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";
  }
})(window.navigator.userAgent.toLowerCase());
console.log(browser);

if(browser === 'ie'){
  // if the browser is IE, remove "display: none" from IE message template
  document.getElementById('ie-message').style.display = 'block';
} else {
  platformBrowserDynamic().bootstrapModule(AppModule).then(ref => {
  // Ensure Angular destroys itself on hot reloads.
  if (window['ngRef']) {
    window['ngRef'].destroy();
  }
  window['ngRef'] = ref;

  // Otherwise, log the boot error
  }).catch(err => console.error(err));
}

  • 发表于 2019-07-05 17:56
  • 阅读 ( 324 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除