Skip to content

Instantly share code, notes, and snippets.

@itsabdessalam
Last active April 19, 2020 14:38
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 itsabdessalam/8e945d7c35a9b2e01a015d9971b13945 to your computer and use it in GitHub Desktop.
Save itsabdessalam/8e945d7c35a9b2e01a015d9971b13945 to your computer and use it in GitHub Desktop.
getDeviceType - Helper to retrieve current device type
/**
* Helper to retrieve current device type
*/
export const getDeviceType = () => {
const ua = navigator.userAgent,
// we could have had several if, a switch with cases, or an object containing keys and values
// by preference and to reduce the process we chose an array of objects containing the type of device and the test
types = [
{
type: "tablet",
value: /(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i.test(ua),
},
{
type: "mobile",
value: /Mobile|iP(hone|od|ad)|Android|BlackBerry|IEMobile|Kindle|Silk-Accelerated|(hpw|web)OS|Opera M(obi|ini)/.test(
ua
)
}
];
try {
return types.find((type) => type.value).type;
} catch (error) {
// if any exception is catched
// return "desktop" by default
return "desktop";
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment