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);
});
요약
- 서비스 워커를 등록하고 필요한 파일을 캐싱합니다.
- 서비스 워커의
activate
이벤트에서 오래된 캐시를 삭제하고 새로운 캐시를 저장합니다. - 서버에서 푸시 알림을 보내어 사용자에게 업데이트를 알리고, 푸시 알림을 클릭하면 페이지를 새로고침하여 최신 콘텐츠를 로드할 수 있습니다.
이 방법을 통해 모바일 환경에서 웹앱의 캐시 데이터를 업데이트하고 최신 콘텐츠를 사용자에게 제공할 수 있습니다.