Skip to content

Instantly share code, notes, and snippets.

@CanRau
Created July 19, 2022 23:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CanRau/ad4dae5789fedae8edeef4c40ec4f9eb to your computer and use it in GitHub Desktop.
Save CanRau/ad4dae5789fedae8edeef4c40ec4f9eb to your computer and use it in GitHub Desktop.
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