browse.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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 result = {
  28. isNode: false,
  29. isMobile: isMobile,
  30. isPC: false,
  31. isDoc: !!staticDocument
  32. }
  33. if (!staticWindow && typeof process !== staticStrUndefined) {
  34. result.isNode = true
  35. } else {
  36. isEdge = isBrowseType('Edge')
  37. isChrome = isBrowseType('Chrome')
  38. isMobile = /(Android|webOS|iPhone|iPad|iPod|SymbianOS|BlackBerry|Windows Phone)/.test(navigator.userAgent)
  39. if (result.isDoc) {
  40. $body = staticDocument.body || staticDocument.documentElement
  41. arrayEach(['webkit', 'khtml', 'moz', 'ms', 'o'], function (core) {
  42. result['-' + core] = !!$body[core + 'MatchesSelector']
  43. })
  44. }
  45. assign(result, {
  46. edge: isEdge,
  47. firefox: isBrowseType('Firefox'),
  48. msie: !isEdge && result['-ms'],
  49. safari: !isChrome && !isEdge && isBrowseType('Safari'),
  50. isMobile: isMobile,
  51. isPC: !isMobile,
  52. isLocalStorage: isBrowseStorage(staticWindow.localStorage),
  53. isSessionStorage: isBrowseStorage(staticWindow.sessionStorage)
  54. })
  55. }
  56. return result
  57. }
  58. module.exports = browse