platform.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. declare const window: any
  2. const ua = navigator.userAgent
  3. const hostname = location.hostname.toLowerCase()
  4. // 在安卓或者ios中
  5. export const androidOrIOS = function () {
  6. const u = ua.toLowerCase()
  7. let agent = ''
  8. if (/iphone|ipod|ipad|ios/.test(u)) {
  9. agent = 'ios'
  10. } else {
  11. agent = 'android'
  12. }
  13. return agent
  14. }
  15. /**
  16. * 用于判断是否在APP容器内
  17. * @returns {boolean}
  18. */
  19. export const getIsInTheAppContainer = function () {
  20. const u = ua.toLowerCase()
  21. // 判断是否在app环境下
  22. let inApp = false
  23. // app调试ua
  24. if (u.includes('jianyuapp')) {
  25. inApp = true
  26. return inApp
  27. }
  28. if (window.JyObj && window.JyObj.mock) {
  29. return inApp
  30. }
  31. try {
  32. if (androidOrIOS() === 'ios') {
  33. const iniOSApp = typeof window.webkit.messageHandlers.skipAppointTab.postMessage === 'function'
  34. inApp = iniOSApp
  35. } else {
  36. const inAndroidApp = typeof window.JyObj !== 'undefined'
  37. inApp = inAndroidApp
  38. }
  39. } catch (e) {
  40. console.warn(e)
  41. inApp = false
  42. }
  43. return inApp
  44. }
  45. export const getIsH5HostName = () => {
  46. return hostname.includes('h5')
  47. }
  48. // 判断是否是微信浏览器
  49. export const inWeiXinBrowser = ua.toLowerCase().indexOf('micromessenger') !== -1
  50. const platformOS = androidOrIOS()
  51. const inApp = getIsInTheAppContainer()
  52. export const getPlatform = () => {
  53. const h5host = getIsH5HostName()
  54. if (inApp) {
  55. return 'app'
  56. } else if (h5host) {
  57. return 'h5'
  58. } else if (inWeiXinBrowser) {
  59. return 'wx'
  60. } else {
  61. return 'h5'
  62. }
  63. }
  64. // 存放基本变量的集合
  65. const _env = {
  66. ua,
  67. platformOS,
  68. platform: getPlatform()
  69. }
  70. // 对基本变量扩展计算的集合
  71. const inH5 = _env.platform === 'h5'
  72. const _envs = {
  73. inWX: _env.platform === 'wx',
  74. inH5,
  75. inApp: inApp,
  76. inAppOrH5: inApp || inH5,
  77. inAndroid: _env.platformOS === 'android',
  78. inIOS: _env.platformOS === 'ios'
  79. }
  80. export const env = _env
  81. export const envs = _envs