브라우저와 그 기능을 감지하는 간단한 React 후크를 만들어 보겠습니다.
User agent sniffing is the most popular approach for browser detection. Unfortunately, it's not very accessible for a front end development because of multiple reasons. Browser vendors constantly trying to make sniffing not possible. Thus, each browser has their own user agent string format, which is very complex to parse.
There is a much more simple way of achieving the same using browser CSS API, which I'm going to show you. So let's create browser capabilities detection React hook.
We are going to use CSS.supports() static method. It returns a boolean value indicating if the browser supports a given CSS feature, or not. This is javascript analog of @supports at-rule. It works similar to media queries, but with CSS capabilities as a subject.
Hook to detect supported features
The most naive approach of calling CSS.supports() during component render cycle will create problems in Server Side Rendering environments, such as Next.js. Because the server side renderer has no access to browser APIs, it just produces a string of code.
import type {FC} from 'react'; const Component: FC = () => { // ? Don't do this! const hasFeature = CSS.supports('your-css-declaration'); // ... }
We will use this simple hook instead. The hook receives a string containing support condition, a CSS rule we are going to validate, e.g. display: flex.
import {useState, useEffect} from 'react'; export const useSupports = (supportCondition: string) => { // Create a state to store declaration check result const [checkResult, setCheckResult] = useState<boolean | undefined>(); useEffect(() => { // Run check as a side effect, on user side only setCheckResult(CSS.supports(supportCondition)); }, [supportCondition]); return checkResult; };
Now we can check for different CSS features support from inside React component. Here is MDN @supports reference
import type {FC} from 'react'; const Component: FC = () => { // Check for native `transform-style: preserve` support const hasNativeTransformSupport = useSupports(' (transform-style: preserve) '); // Check for vendor prefixed `transform-style: preserve` support const hasNativeTransformSupport = useSupports(' (-moz-transform-style: preserve) or (-webkit-transform-style: preserve) '); // ... }
Detect user browser using CSS support conditions
In order to detect user browser, we have to do a little hacking.
Browser hack has nothing to do with law violations. It's just a special CSS declaration or selector which works differently in one of available browsers.
Here is the reference page with various browser hacks. After thorough experimentation on my machine, I've chosen these:
const hacksMapping = { // anything -moz will work, I assume firefox: '-moz-appearance:none', safari: '-webkit-hyphens:none', // tough one because Webkit and Blink are relatives chrome: ' not (-webkit-hyphens:none)) and (not (-moz-appearance:none)) and (list-style-type:"*"' }
And here is our final hook look like:
export const useDetectBrowser = () => { const isFirefox = useSupports(hacksMapping.firefox); const isChrome = useSupports(hacksMapping.chrome); const isSafari = useSupports(hacksMapping.safari); return [ {browser: 'firefox', condition: isFirefox}, {browser: 'chromium based', condition: isChrome}, {browser: 'safari', condition: isSafari}, ].find(({condition}) => condition)?.browser as 'firefox' | 'chromium based' | 'safari' | undefined; };
Full demo
Here is a full working demo of the hook.
Final thoughts
I can't say that this is a bullet-proof, stable approach. Browsers get updated, vendor properties are abandoned or superseded by standard very often. At the same time, I can say this about user agent sniffing. Both ways have similar problems. But CSS.contains() is easier to maintain, and it's much more granular. It welcomes developers to use graceful degradation or progressive enhancement approach and apply their patches granularly.
위 내용은 브라우저와 그 기능을 감지하는 간단한 React 후크를 만들어 보겠습니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











그것은#039; VUE 팀에게 그것을 끝내는 것을 축하합니다. 나는 그것이 막대한 노력과 오랜 시간이라는 것을 알고 있습니다. 모든 새로운 문서도 있습니다.

나는 누군가이 매우 합법적 인 질문으로 글을 썼습니다. Lea는 브라우저에서 유효한 CSS 속성 자체를 얻는 방법에 대해 블로그를 작성했습니다. 이는 이와 같습니다.

다른 날, 나는 Corey Ginnivan의 웹 사이트에서 스크롤 할 때 카드 모음이 서로 쌓이는 것을 발견했습니다.

WordPress 편집기에서 사용자에게 직접 문서를 표시 해야하는 경우 가장 좋은 방법은 무엇입니까?

목표가 귀하의 사이트를 동시에 다른 크기로 표시하는 이러한 데스크탑 앱이 많이 있습니다. 예를 들어, 글을 쓸 수 있습니다

CSS 그리드는 레이아웃이 그 어느 때보 다 쉽게 레이아웃을 만들 수 있도록 설계된 속성 모음입니다. 어쨌든, 약간의 학습 곡선이 있지만 그리드는

플렉스 레이아웃의 보라색 슬래시 영역에 대한 질문 플렉스 레이아웃을 사용할 때 개발자 도구 (d ...)와 같은 혼란스러운 현상이 발생할 수 있습니다.
