Created
July 19, 2022 23:50
-
-
Save CanRau/ad4dae5789fedae8edeef4c40ec4f9eb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useEffect, useState } from "react"; | |
// @NOTE: It's stringifying as I'm storing the result in a form field and then DB, but you can of course change that to your needs | |
// @NOTE: Also `getHighEntropyValues` might throw as mentioned in https://developer.mozilla.org/en-US/docs/Web/API/NavigatorUAData/getHighEntropyValues#exceptions | |
// @NOTE: so when it errors I'm returning the more "basic" `navigator?.userAgentData` with the error information, which might be unnecessary, but I'm curious 🤷🏻♂️ | |
export const useUserAgentClientHints = () => { | |
const [userAgent, setUserAgent] = useState(""); | |
useEffect(() => { | |
if (userAgent) return; | |
navigator?.userAgentData | |
?.getHighEntropyValues?.([ | |
"architecture", | |
"model", | |
"bitness", | |
"platform", | |
"platformVersion", | |
"fullVersionList", | |
]) | |
.then((ua) => setUserAgent(JSON.stringify(ua))) | |
.catch((err: DOMException) => | |
setUserAgent( | |
JSON.stringify({ | |
userAgentData: navigator?.userAgentData, | |
error: { name: err?.name, code: err?.code, message: err?.message }, | |
}), | |
), | |
); | |
}); | |
return userAgent; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment