ReactJS中的浏览器检测 [英] Browser Detection in ReactJS

查看:1000
本文介绍了ReactJS中的浏览器检测的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there any way to detect IE browser with React and either redirect to a page or give any helpful message. I found something in JavaScript, but not sure how would I use it with React+TypeScript.

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

推荐答案

你在正确的轨道上可以有条件地使用它们渲染jsx或帮助路由......

You are on the right track you can use these to conditionally render jsx or help with routing...

我使用了以下内容并取得了巨大成功。

I have used the following with great success.

最初来自 - 如何检测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;

请注意,由于浏览器更改,每个人都有机会弃用。

Please be aware they each stand a chance to deprecated due to browser changes.

我在这样的反应中使用它们。

I use them in react like this.

 content(props){
    if(!isChrome){
     return (
      <Otherjsxelements/>
     )
    }
    else { 
     return (
      <Chromejsxelements/>
     )
    }
  }

然后通过调用主组件中的{this.Content()}来呈现不同的浏览器特定元素。

Then by calling {this.Content()} in my main component to render the different browser specific elements.

Sudo代码可能看起来像这样......(未经测试)。

Sudo code might look something like this... (untested).

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()}
        )
    }
}

这篇关于ReactJS中的浏览器检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆