common.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. // Setup the animation loop.
  2. import TWEEN from '@tweenjs/tween.js'
  3. function animate (time) {
  4. requestAnimationFrame(animate)
  5. TWEEN.update(time)
  6. }
  7. requestAnimationFrame(animate)
  8. if ('serviceWorker' in navigator) {
  9. let scriptUrl = '/sw.js'
  10. navigator.serviceWorker.register(scriptUrl).then(function (reg) {
  11. if (reg.installing) {
  12. console.log('Service worker installing')
  13. } else if (reg.waiting) {
  14. console.log('Service worker installed')
  15. } else if (reg.active) {
  16. console.log('Service worker active')
  17. }
  18. reg.addEventListener('updatefound', function () {
  19. if (navigator.serviceWorker.controller) {
  20. var installingWorker = reg.installing
  21. installingWorker.onstatechange = function () {
  22. console.log('installingWorker.state:' + installingWorker.state)
  23. switch (installingWorker.state) {
  24. case 'installed':
  25. // MessageBox.confirm('新的内容已更新完毕,立即刷新页面?', '提示', {
  26. // confirmButtonText: '确定',
  27. // cancelButtonText: '取消'
  28. // }).then(() => {
  29. // location.reload()
  30. // }).catch(() => {})
  31. break
  32. case 'redundant':
  33. break
  34. default:
  35. }
  36. }
  37. }
  38. })
  39. if (navigator.serviceWorker) {
  40. navigator.serviceWorker.addEventListener('statechange', function (e) {
  41. console.log('statechange: ', e.target.state)
  42. })
  43. }
  44. }).catch(function (error) {
  45. // registration failed
  46. console.log('Registration failed with ' + error)
  47. })
  48. }
  49. // 监听localStorage的变化,user_id变化时,要刷新
  50. window.addEventListener('storage', (event) => {
  51. if (event.key === 'user_id') {
  52. location.reload()
  53. }
  54. })
  55. // 触发pwa的安装实践
  56. var btnPwa = null
  57. var deferredPrompt = null
  58. window.addEventListener('beforeinstallprompt', function (e) {
  59. if (!btnPwa) {
  60. initPwaBtn()
  61. }
  62. deferredPrompt = e
  63. // 取消默认事件
  64. e.preventDefault()
  65. return false
  66. })
  67. function initPwaBtn () {
  68. btnPwa = document.getElementById('btnPwa')
  69. if (!btnPwa) {
  70. return
  71. }
  72. btnPwa.style.display = 'block'
  73. btnPwa.addEventListener('click', function () {
  74. if (deferredPrompt != null) {
  75. deferredPrompt.prompt()
  76. // 检测用户的安装行为
  77. deferredPrompt.userChoice.then(function (choiceResult) {
  78. console.log(choiceResult.outcome)
  79. if (choiceResult.outcome === 'dismissed') {
  80. console.log('用户取消安装应用')
  81. } else {
  82. console.log('用户安装了应用')
  83. btnPwa.style.display = 'none'
  84. }
  85. })
  86. deferredPrompt = null
  87. }
  88. })
  89. }