Last active
April 19, 2020 14:38
-
-
Save itsabdessalam/8e945d7c35a9b2e01a015d9971b13945 to your computer and use it in GitHub Desktop.
getDeviceType - Helper to retrieve current device type
This file contains hidden or 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
/** | |
* 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