browser.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. function getTypeVersion() {
  2. const userAgent = navigator.userAgent.toLowerCase();
  3. const browserTypes = {
  4. IE: /(?:msie|trident.*rv).([\d.]+)/,
  5. Edge: /edge.([\d.]+)/,
  6. Chrome: /chrome.([\d.]+)/,
  7. Firefox: /firefox.([\d.]+)/,
  8. Opera: /opera.([\d.]+)/,
  9. Safari: /(?:safari|version).([\d.]+)/,
  10. };
  11. type BrowserKeys = keyof typeof browserTypes;
  12. /** browser type */
  13. let type!: BrowserKeys | null;
  14. /** browser version */
  15. let version!: string | null;
  16. for (type in browserTypes) {
  17. if ((version = browserTypes[type as BrowserKeys].exec(userAgent) as any)) {
  18. version = version[1];
  19. break;
  20. }
  21. }
  22. if (version) {
  23. if (type === 'IE') {
  24. try {
  25. document.execCommand('BackgroundImageCache', false, true as any);
  26. } catch (error) {
  27. console.log(error);
  28. }
  29. }
  30. } else {
  31. type = version = null;
  32. }
  33. return { type, version };
  34. }
  35. const { type, version } = getTypeVersion();
  36. export function getType() {
  37. return type;
  38. }
  39. export function getVersion() {
  40. return version;
  41. }
  42. export function isIeFn() {
  43. return type === 'IE';
  44. }
  45. export function isChromeFn() {
  46. return type === 'Chrome';
  47. }
  48. export function isEdgeFn() {
  49. return type === 'Edge';
  50. }
  51. export function isSafariFn() {
  52. return type === 'Safari';
  53. }
  54. export function isFirefoxFn() {
  55. return type === 'Firefox';
  56. }
  57. export function isOperaFn() {
  58. return type === 'Opera';
  59. }
  60. /**
  61. * set page Title
  62. * @param {*} title :page Title
  63. */
  64. function setDocumentTitle(title: string) {
  65. document.title = title;
  66. const ua = navigator.userAgent;
  67. const regex = /\bMicroMessenger\/([\d.]+)/;
  68. // 兼容
  69. if (regex.test(ua) && /ip(hone|od|ad)/i.test(ua)) {
  70. const i = document.createElement('iframe');
  71. i.src = '/favicon.ico';
  72. i.style.display = 'none';
  73. i.onload = function () {
  74. setTimeout(function () {
  75. i.remove();
  76. }, 9);
  77. };
  78. document.body.appendChild(i);
  79. }
  80. }
  81. export function setTitle(title: string, appTitle?: string) {
  82. if (title) {
  83. const _title = title ? ` ${title}-${appTitle} ` : `${appTitle}`;
  84. setDocumentTitle(_title);
  85. }
  86. }