ReactJS 中的浏览器检测

新手上路,请多包涵

有没有办法用 React 检测 IE 浏览器并重定向到页面或提供任何有用的消息。我在 JavaScript 中找到了一些东西,但不确定如何将它与 React+TypeScript 一起使用。

var isEdge = !isIE && !!window.StyleMedia;

原文由 Hafiz Temuri 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 993
2 个回答

您走在正确的轨道上,您可以使用它们有条件地渲染 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()}
        )
    }
}

原文由 Shawn Matthews 发布,翻译遵循 CC BY-SA 4.0 许可协议

有一个新的包可以为 React 处理这个问题: https ://www.npmjs.com/package/react-browser-navigator

这是您可以使用它的方式:

 // import the module
import useNavigator from "react-browser-navigator";

function App() {
  // importing the property
  let { userAgent } = useNavigator();

  // you can use it within the useEffect hook OR simply print the
  // string into the return statement
  useEffect(() => {
    if (!isNull(userAgent)) {
      // printing out the entire object
      console.log("userAgent", userAgent);
    }
  }, [userAgent]);

  return (
    <div>
      <span>userAgent:</span> {userAgent}
    </div>
  );
}

本质上,输出将是这样的:

 Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36

原文由 David Kutas 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题