get-device.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import { getWindow } from 'ssr-window';
  2. import { getSupport } from './get-support.js';
  3. let deviceCached;
  4. function calcDevice({
  5. userAgent
  6. } = {}) {
  7. const support = getSupport();
  8. const window = getWindow();
  9. const platform = window.navigator.platform;
  10. const ua = userAgent || window.navigator.userAgent;
  11. const device = {
  12. ios: false,
  13. android: false
  14. };
  15. const screenWidth = window.screen.width;
  16. const screenHeight = window.screen.height;
  17. const android = ua.match(/(Android);?[\s\/]+([\d.]+)?/); // eslint-disable-line
  18. let ipad = ua.match(/(iPad).*OS\s([\d_]+)/);
  19. const ipod = ua.match(/(iPod)(.*OS\s([\d_]+))?/);
  20. const iphone = !ipad && ua.match(/(iPhone\sOS|iOS)\s([\d_]+)/);
  21. const windows = platform === 'Win32';
  22. let macos = platform === 'MacIntel';
  23. // iPadOs 13 fix
  24. const iPadScreens = ['1024x1366', '1366x1024', '834x1194', '1194x834', '834x1112', '1112x834', '768x1024', '1024x768', '820x1180', '1180x820', '810x1080', '1080x810'];
  25. if (!ipad && macos && support.touch && iPadScreens.indexOf(`${screenWidth}x${screenHeight}`) >= 0) {
  26. ipad = ua.match(/(Version)\/([\d.]+)/);
  27. if (!ipad) ipad = [0, 1, '13_0_0'];
  28. macos = false;
  29. }
  30. // Android
  31. if (android && !windows) {
  32. device.os = 'android';
  33. device.android = true;
  34. }
  35. if (ipad || iphone || ipod) {
  36. device.os = 'ios';
  37. device.ios = true;
  38. }
  39. // Export object
  40. return device;
  41. }
  42. function getDevice(overrides = {}) {
  43. if (!deviceCached) {
  44. deviceCached = calcDevice(overrides);
  45. }
  46. return deviceCached;
  47. }
  48. export { getDevice };