kyber

Форк
0
/
serviceWorkerRegistration.ts 
142 строки · 5.1 Кб
1
// This optional code is used to register a service worker.
2
// register() is not called by default.
3

4
// This lets the app load faster on subsequent visits in production, and gives
5
// it offline capabilities. However, it also means that developers (and users)
6
// will only see deployed updates on subsequent visits to a page, after all the
7
// existing tabs open on the page have been closed, since previously cached
8
// resources are updated in the background.
9

10
// To learn more about the benefits of this model and instructions on how to
11
// opt-in, read https://cra.link/PWA
12

13
const isLocalhost = Boolean(
14
  window.location.hostname === 'localhost' ||
15
    // [::1] is the IPv6 localhost address.
16
    window.location.hostname === '[::1]' ||
17
    // 127.0.0.0/8 are considered localhost for IPv4.
18
    window.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/)
19
)
20

21
type Config = {
22
  onSuccess?: (registration: ServiceWorkerRegistration) => void;
23
  onUpdate?: (registration: ServiceWorkerRegistration) => void;
24
};
25

26
export function register(config?: Config) {
27
  if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
28
    // The URL constructor is available in all browsers that support SW.
29
    const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href)
30
    if (publicUrl.origin !== window.location.origin) {
31
      // Our service worker won't work if PUBLIC_URL is on a different origin
32
      // from what our page is served on. This might happen if a CDN is used to
33
      // serve assets; see https://github.com/facebook/create-react-app/issues/2374
34
      return
35
    }
36

37
    window.addEventListener('load', () => {
38
      const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`
39

40
      if (isLocalhost) {
41
        // This is running on localhost. Let's check if a service worker still exists or not.
42
        checkValidServiceWorker(swUrl, config)
43

44
        // Add some additional logging to localhost, pointing developers to the
45
        // service worker/PWA documentation.
46
        navigator.serviceWorker.ready.then(() => {
47
          console.log(
48
            'This web app is being served cache-first by a service ' +
49
              'worker. To learn more, visit https://cra.link/PWA'
50
          )
51
        })
52
      } else {
53
        // Is not localhost. Just register service worker
54
        registerValidSW(swUrl, config)
55
      }
56
    })
57
  }
58
}
59

60
function registerValidSW(swUrl: string, config?: Config) {
61
  navigator.serviceWorker
62
    .register(swUrl)
63
    .then((registration) => {
64
      registration.onupdatefound = () => {
65
        const installingWorker = registration.installing
66
        if (installingWorker == null) {
67
          return
68
        }
69
        installingWorker.onstatechange = () => {
70
          if (installingWorker.state === 'installed') {
71
            if (navigator.serviceWorker.controller) {
72
              // At this point, the updated precached content has been fetched,
73
              // but the previous service worker will still serve the older
74
              // content until all client tabs are closed.
75
              console.log(
76
                'New content is available and will be used when all ' +
77
                  'tabs for this page are closed. See https://cra.link/PWA.'
78
              )
79

80
              // Execute callback
81
              if (config && config.onUpdate) {
82
                config.onUpdate(registration)
83
              }
84
            } else {
85
              // At this point, everything has been precached.
86
              // It's the perfect time to display a
87
              // "Content is cached for offline use." message.
88
              console.log('Content is cached for offline use.')
89

90
              // Execute callback
91
              if (config && config.onSuccess) {
92
                config.onSuccess(registration)
93
              }
94
            }
95
          }
96
        }
97
      }
98
    })
99
    .catch((error) => {
100
      console.error('Error during service worker registration:', error)
101
    })
102
}
103

104
function checkValidServiceWorker(swUrl: string, config?: Config) {
105
  // Check if the service worker can be found. If it can't reload the page.
106
  fetch(swUrl, {
107
    headers: { 'Service-Worker': 'script' },
108
  })
109
    .then((response) => {
110
      // Ensure service worker exists, and that we really are getting a JS file.
111
      const contentType = response.headers.get('content-type')
112
      if (
113
        response.status === 404 ||
114
        (contentType != null && contentType.indexOf('javascript') === -1)
115
      ) {
116
        // No service worker found. Probably a different app. Reload the page.
117
        navigator.serviceWorker.ready.then((registration) => {
118
          registration.unregister().then(() => {
119
            window.location.reload()
120
          })
121
        })
122
      } else {
123
        // Service worker found. Proceed as normal.
124
        registerValidSW(swUrl, config)
125
      }
126
    })
127
    .catch(() => {
128
      console.log('No internet connection found. App is running in offline mode.')
129
    })
130
}
131

132
export function unregister() {
133
  if ('serviceWorker' in navigator) {
134
    navigator.serviceWorker.ready
135
      .then((registration) => {
136
        registration.unregister()
137
      })
138
      .catch((error) => {
139
        console.error(error.message)
140
      })
141
  }
142
}

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.