browse.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. var staticStrUndefined = require('./staticStrUndefined')
  2. var staticDocument = require('./staticDocument')
  3. var staticWindow = require('./staticWindow')
  4. var assign = require('./assign')
  5. var arrayEach = require('./arrayEach')
  6. /* eslint-disable valid-typeof */
  7. function isBrowseStorage (storage) {
  8. try {
  9. var testKey = '__xe_t'
  10. storage.setItem(testKey, 1)
  11. storage.removeItem(testKey)
  12. return true
  13. } catch (e) {
  14. return false
  15. }
  16. }
  17. function isBrowseType (type) {
  18. return navigator.userAgent.indexOf(type) > -1
  19. }
  20. /**
  21. * 获取浏览器内核
  22. * @return Object
  23. */
  24. function browse () {
  25. var $body, isChrome, isEdge
  26. var isMobile = false
  27. var isLocalStorage = false
  28. var isSessionStorage = false
  29. var result = {
  30. isNode: false,
  31. isMobile: isMobile,
  32. isPC: false,
  33. isDoc: !!staticDocument
  34. }
  35. if (!staticWindow && typeof process !== staticStrUndefined) {
  36. result.isNode = true
  37. } else {
  38. isEdge = isBrowseType('Edge')
  39. isChrome = isBrowseType('Chrome')
  40. isMobile = /(Android|webOS|iPhone|iPad|iPod|SymbianOS|BlackBerry|Windows Phone)/.test(navigator.userAgent)
  41. if (result.isDoc) {
  42. $body = staticDocument.body || staticDocument.documentElement
  43. arrayEach(['webkit', 'khtml', 'moz', 'ms', 'o'], function (core) {
  44. result['-' + core] = !!$body[core + 'MatchesSelector']
  45. })
  46. }
  47. try {
  48. isLocalStorage = isBrowseStorage(staticWindow.localStorage)
  49. } catch(e) {}
  50. try {
  51. isSessionStorage = isBrowseStorage(staticWindow.sessionStorage)
  52. } catch(e) {}
  53. assign(result, {
  54. edge: isEdge,
  55. firefox: isBrowseType('Firefox'),
  56. msie: !isEdge && result['-ms'],
  57. safari: !isChrome && !isEdge && isBrowseType('Safari'),
  58. isMobile: isMobile,
  59. isPC: !isMobile,
  60. isLocalStorage: isLocalStorage,
  61. isSessionStorage: isSessionStorage
  62. })
  63. }
  64. return result
  65. }
  66. module.exports = browse