有什么方法可以使用 React 检测 IE 浏览器并重定向到页面或提供任何有用的消息。我在 JavaScript 中找到了一些东西,但不确定如何将它与 React+TypeScript 一起使用。
var isEdge = !isIE && !!window.StyleMedia;
有什么方法可以使用 React 检测 IE 浏览器并重定向到页面或提供任何有用的消息。我在 JavaScript 中找到了一些东西,但不确定如何将它与 React+TypeScript 一起使用。
var isEdge = !isIE && !!window.StyleMedia;
您走在正确的轨道上,您可以使用这些来有条件地呈现 jsx 或帮助路由...
我已经成功地使用了以下内容。
最初来自 -如何检测 Safari、Chrome、IE、Firefox 和 Opera 浏览器?
// Opera 8.0+
const isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
// Firefox 1.0+
const isFirefox = typeof InstallTrigger !== 'undefined';
// Safari 3.0+ "[object HTMLElementConstructor]" 
const isSafari = /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || (typeof safari !== 'undefined' && safari.pushNotification));
// Internet Explorer 6-11
const isIE = /*@cc_on!@*/false || !!document.documentMode;
// Edge 20+
const isEdge = !isIE && !!window.StyleMedia;
// Chrome 1 - 71
const isChrome = !!window.chrome && (!!window.chrome.webstore || !!window.chrome.runtime);
// Blink engine detection
const isBlink = (isChrome || isOpera) && !!window.CSS;
请注意,由于浏览器的变化,它们都有可能被弃用。
我在 React 中像这样使用它们:
 content(props){
    if(!isChrome){
     return (
      <Otherjsxelements/>
     )
    }
    else { 
     return (
      <Chromejsxelements/>
     )
    }
  }
然后通过在我的主要组件中调用 {this.Content()} 来呈现不同的浏览器特定元素。
伪代码可能看起来像这样......(未经测试):
import React from 'react';
const isChrome = !!window.chrome && (!!window.chrome.webstore || !!window.chrome.runtime);
export default class Test extends React.Component {
  content(){
    if(isChrome){
        return (
            <div>Chrome</div>
        )
    } else {
        return (
            <div>Not Chrome</div>
        )
    }
  }
    render() {
        return (
            <div>Content to be seen on all browsers</div>
            {this.content()}
        )
    }
}
不知道为什么,但没有人提到这个包:react-device-detect 这个包有很多浏览器检查,加上版本和其他一些相关的信息。它真的很小,而且已经更新。
您可以使用:
import { isIE } from 'react-device-detect';
isIE // returns true or false
react-device-detect 它也是非常小的捆绑恐惧症链接
这是我在进行基于 JS/Browser 的浏览器检测时总是使用的服务:http : //is.js.org/
if (is.ie() || is.edge()) {
  window.location.href = 'http://example.com';
}
尝试:
const isEdge = window.navigator.userAgent.indexOf('Edge') != -1
const isIE = window.navigator.userAgent.indexOf('Trident') != -1 && !isEdge
等等。
每个浏览器都有一个不同的用户代理,您可以检查。
这些当然可以由客户伪造,但在我看来,这是一个更可靠的长期解决方案。
您可以像这样为 IE 编写测试。
<script>
     // Internet Explorer 6-11
          const isIE = document.documentMode;
          if (isIE){
            window.alert(
              "Your MESSAGE here."
            )
          }
</script>