programing

React에서의 브라우저 검출JS

muds 2023. 3. 17. 22:05
반응형

React에서의 브라우저 검출JS

React로 IE 브라우저를 검출하여 페이지로 리다이렉트하거나 도움이 되는 메시지를 보낼 수 있는 방법이 있습니까?JavaScript에서 무언가를 찾았는데, React+TypeScript에서 어떻게 사용할지 잘 모르겠습니다.

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

올바른 방향으로 가고 있습니다.이것들을 사용하여 jsx를 조건부로 렌더링하거나 라우팅에 도움을 줄 수 있습니다.

저는 아래를 잘 활용했습니다.

원본 - Safari, Chrome, IE, FirefoxOpera 브라우저를 검색하는 방법

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

브라우저 변경으로 인해 각각 권장되지 않을 수 있다는 점에 유의하시기 바랍니다.

리액트에서는 다음과 같이 사용합니다.

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

그럼 {이것}을(를) 부르면 됩니다.다른 브라우저 고유의 요소를 렌더링하기 위해 메인 컴포넌트에 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';
}

나는 개츠비를 리액트 사이트에 사용하고 있었고 빌드는 나에게 받아들여진 대답에 문제를 일으키고 있었다.그래서 나는 결국 그것을 사용했다.useEffect최소한 IE에 대해 렌더링할 수 없는 경우:

  const [isIE, setIsIE] = React.useState(false);

  React.useEffect(() => {
    console.log(`UA: ${window.navigator.userAgent}`);
    var msie = window.navigator.userAgent.indexOf("MSIE ");
    setIsIE(msie > 0)
  }, []);

  if(isIE) {
    return <></>
  }

// In my component render

if(isIE) { return <></> }

아이디어는 원래 다음과 같습니다.

https://medium.com/react-review/how-to-create-a-custom-usedevicedetect-react-hook-f5a1bfe64599

그리고.

사용자가 IE를 사용하고 있는지 확인합니다.

시험:

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>

거의 망가질 뻔했는데, 아주 단순하고 간단해 보이는 것을 발견했어요. 벤더 이름을 사용하세요.즉, 구글, 애플 등 navigator.vendor.includes('Apple')이게 누군가 도움이 됐으면 좋겠어요

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

다음은 클라이언트의 브라우저에서 얻을 수 있는 모든 정보입니다(react 사용).

    let latitude
    let longitude
    const location = window.navigator && window.navigator.geolocation

    if (location) {
      location.getCurrentPosition(position => {
        latitude = position.coords.latitude
        longitude = position.coords.longitude
      })
    }

    var info = {
      timeOpened: new Date(),
      timezone: new Date().getTimezoneOffset() / 60,
      pageon: window.location.pathname,
      referrer: document.referrer,
      previousSites: window.history.length,
      browserName: window.navigator.appName,
      browserEngine: window.navigator.product,
      browserVersion1a: window.navigator.appVersion,
      browserVersion1b: navigator.userAgent,
      browserLanguage: navigator.language,
      browserOnline: navigator.onLine,
      browserPlatform: navigator.platform,
      javaEnabled: navigator.javaEnabled(),
      dataCookiesEnabled: navigator.cookieEnabled,
      dataCookies1: document.cookie,
      dataCookies2: decodeURIComponent(document.cookie.split(';')),
      dataStorage: localStorage,
      sizeScreenW: window.screen.width,
      sizeScreenH: window.screen.height,
      sizeDocW: window.document.width,
      sizeDocH: window.document.height,
      sizeInW: window.innerWidth,
      sizeInH: window.innerHeight,
      sizeAvailW: window.screen.availWidth,
      sizeAvailH: window.screen.availHeight,
      scrColorDepth: window.screen.colorDepth,
      scrPixelDepth: window.screen.pixelDepth,
      latitude,
      longitude
    }
    console.log(info)

는 「」입니다.browserName

다음과 같이 시험해 보십시오.

navigator.browserDetection= (function(){
    var ua= navigator.userAgent, tem, 
    M= ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
    if(/trident/i.test(M[1])){
        tem=  /\brv[ :]+(\d+)/g.exec(ua) || [];
        return 'IE '+(tem[1] || '');
    }
    if(M[1]=== 'Chrome'){
        tem= ua.match(/\b(OPR|Edge)\/(\d+)/);
        if(tem!= null) return tem.slice(1).join(' ').replace('OPR', 'Opera');
    }
    M= M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
    if((tem= ua.match(/version\/(\d+)/i))!= null) M.splice(1, 1, tem[1]);
    return M.join(' ');
})();

console.log(navigator.browserDetection); // outputs: `Chrome 92`

언급URL : https://stackoverflow.com/questions/49328382/browser-detection-in-reactjs

반응형