get-device.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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'; // iPadOs 13 fix
  23. const iPadScreens = ['1024x1366', '1366x1024', '834x1194', '1194x834', '834x1112', '1112x834', '768x1024', '1024x768', '820x1180', '1180x820', '810x1080', '1080x810'];
  24. if (!ipad && macos && support.touch && iPadScreens.indexOf(`${screenWidth}x${screenHeight}`) >= 0) {
  25. ipad = ua.match(/(Version)\/([\d.]+)/);
  26. if (!ipad) ipad = [0, 1, '13_0_0'];
  27. macos = false;
  28. } // Android
  29. if (android && !windows) {
  30. device.os = 'android';
  31. device.android = true;
  32. }
  33. if (ipad || iphone || ipod) {
  34. device.os = 'ios';
  35. device.ios = true;
  36. } // Export object
  37. return device;
  38. }
  39. function getDevice(overrides = {}) {
  40. if (!deviceCached) {
  41. deviceCached = calcDevice(overrides);
  42. }
  43. return deviceCached;
  44. }
  45. export { getDevice };