sitelink1  
sitelink2  
sitelink3  

모바일 환경에서 웹앱의 캐시 데이터를 서비스에서 업데이트로 갱신하는 방법은 서비스 워커(Service Worker)를 사용하는 것입니다.

서비스 워커는 백그라운드에서 실행되어 네트워크 요청을 가로채고, 오프라인 모드에서도 웹 애플리케이션을 사용할 수 있게 해줍니다.

또한, 새로운 콘텐츠를 미리 캐싱하여 사용자에게 최신 콘텐츠를 제공할 수 있습니다.

다음은 서비스 워커를 설정하고, 캐시 데이터를 업데이트하는 예제입니다:

1. 서비스 워커 파일 (service-worker.js)

const CACHE_NAME = 'my-app-cache-v1';
const urlsToCache = [
  '/',
  '/index.html',
  '/styles.css',
  '/app.js',
  // 기타 필요한 파일들
];

// 서비스 워커 설치 이벤트
self.addEventListener('install', event => {
  event.waitUntil(
    caches.open(CACHE_NAME)
.then(cache => {
        return cache.addAll(urlsToCache);
      })
  );
});

// 서비스 워커 활성화 이벤트
self.addEventListener('activate', event => {
  const cacheWhitelist = [CACHE_NAME];
  event.waitUntil(
caches.keys().then(cacheNames => {
      return Promise.all(
cacheNames.map(cacheName => {
          if (!cacheWhitelist.includes(cacheName)) {
            return caches.delete(cacheName);
          }
        })
      );
    })
  );
});

// 서비스 워커 페치 이벤트
self.addEventListener('fetch', event => {
  event.respondWith(
    caches.match(event.request)
.then(response => {
        if (response) {
          return response;
        }
        return fetch(event.request).then(
response => {
            if (!response || response.status !== 200 || response.type !== 'basic') {
              return response;
            }
            const responseToCache = response.clone();
            caches.open(CACHE_NAME)
.then(cache => {
                cache.put(event.request, responseToCache);
              });
            return response;
          }
        );
      })
  );
});

2. 서비스 워커 등록 (main.js)

if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/service-worker.js').then(registration => {
      console.log('Service Worker registered with scope:', registration.scope);
}).catch(error => {
      console.log('Service Worker registration failed:', error);
    });
  });
}

3. HTML 파일 (index.html)

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>My Web App</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <h1>Hello, World!</h1>
  <script src="app.js"></script>
  <script src="main.js"></script>
</body>
</html>

4. 캐시 갱신 로직

서비스 워커의 activate 이벤트에서 오래된 캐시를 삭제하여 새로운 캐시를 저장할 수 있습니다.

위의 service-worker.js 파일에서 캐시 갱신 로직은 이미 포함되어 있습니다.

이 로직은 새로운 서비스 워커가 활성화될 때, 이전 캐시를 삭제하고 새로운 캐시를 저장합니다.

5. 푸시 알림을 통한 캐시 갱신

서버에서 푸시 알림을 보내어 웹앱이 백그라운드에서 업데이트를 받도록 할 수도 있습니다.

이를 위해 푸시 알림 API를 사용할 수 있습니다.

self.addEventListener('push', event => {
  const data = event.data.json();
  const title = data.title || 'New Content Available';
  const options = {
    body: data.body || 'Click to refresh',
    icon: data.icon || '/icon.png',
    badge: data.badge || '/badge.png'
  };

  event.waitUntil(
    self.registration.showNotification(title, options)
  );
});

// 알림 클릭 이벤트
self.addEventListener('notificationclick', event => {
  event.notification.close();
  event.waitUntil(
clients.matchAll({ type: 'window' }).then(clientList => {
      if (clients.openWindow) {
        return clients.openWindow('/');
      }
    })
  );
});

서버에서 푸시 메시지를 보내는 예제 (Node.js):

const webPush = require('web-push');

const vapidKeys = {
  publicKey: 'YOUR_PUBLIC_KEY',
  privateKey: 'YOUR_PRIVATE_KEY'
};

webPush.setVapidDetails(
  'mailto:your-email@example.com',
  vapidKeys.publicKey,
  vapidKeys.privateKey
);

const subscription = {
  endpoint: 'YOUR_SUBSCRIBER_ENDPOINT',
  keys: {
    p256dh: 'YOUR_P256DH_KEY',
    auth: 'YOUR_AUTH_KEY'
  }
};

const payload = JSON.stringify({
  title: 'New Content Available',
  body: 'Click to refresh',
  icon: '/icon.png',
  badge: '/badge.png'
});

webPush.sendNotification(subscription, payload).catch(error => {
  console.error('Error sending push notification:', error);
});

요약

  1. 서비스 워커를 등록하고 필요한 파일을 캐싱합니다.
  2. 서비스 워커의 activate 이벤트에서 오래된 캐시를 삭제하고 새로운 캐시를 저장합니다.
  3. 서버에서 푸시 알림을 보내어 사용자에게 업데이트를 알리고, 푸시 알림을 클릭하면 페이지를 새로고침하여 최신 콘텐츠를 로드할 수 있습니다.

이 방법을 통해 모바일 환경에서 웹앱의 캐시 데이터를 업데이트하고 최신 콘텐츠를 사용자에게 제공할 수 있습니다.

번호 제목 글쓴이 날짜 조회 수
29 [mdn web docs] Service worker를 사용해 PWA를 오프라인에서 동작하게 만들기 황제낙엽 2024.07.20 121
» [ChatGPT] 모바일 환경에서 웹앱의 캐시(cache) 데이터를 서비스에서 업데이트로 갱신하는 방법 황제낙엽 2024.07.17 127
27 [ChatGPT] service-worker.js 에서 cache file list 를 동적으로 생성하여 적용하기 황제낙엽 2024.07.17 105
26 (Copilot) PWA Builder 에 대하여 황제낙엽 2024.07.05 171
25 PWA 데모 샘플들 file 황제낙엽 2024.07.04 152
24 FirebaseMessagingException: Requested entity was not found. 황제낙엽 2024.01.12 1509
23 PWA 관련 서적 두권에 대한 목차와 후기 황제낙엽 2023.11.29 119
22 (Copilot) Admin SDK Reference의 java 라이브러리를 이용하여 notification을 fcm에 전송하는 java 예제 황제낙엽 2023.11.28 205
21 firebase.messaging().getToken() 함수와 pushManager.subscribe() 함수의 관계 황제낙엽 2023.11.26 275
20 service worker 재작성시 수동 업데이트 file 황제낙엽 2023.11.25 115
19 [POST/2023.09.13] PWA (Progressive Web Apps) 관련 황제낙엽 2023.11.24 98
18 [POST/2019.11.25] 브라우저 알림(Notification) 팝업에 버튼 추가 with ServiceWorker file 황제낙엽 2023.11.24 99
17 [FCM] FCM 으로 알림 전송 테스트 (spring boot + android + fcm rest) 황제낙엽 2023.11.24 178
16 [FCM] Firebase Console 에서 메세지 보내기 file 황제낙엽 2023.11.24 156
15 (OMNIBUSCODE/FCM/WEB/JAVA) web push notification (web browser) 샘플 file 황제낙엽 2023.11.23 146
14 (Copilot) Notification Server 의 종류 황제낙엽 2023.11.23 141
13 (OMNIBUSCODE/FCM/WEB/JAVA) web push notification (web browser) 구현 절차 [1] 황제낙엽 2023.11.20 190
12 서비스 워커(service worker) 등록에 대한 LLM 챗봇의 답변 황제낙엽 2023.11.20 113
11 service worker 개발 참고용 링크 모음 황제낙엽 2023.11.10 124
10 service worker 개발을 위한 mozilla 공식 문서 file 황제낙엽 2023.11.10 103