106 lines
3.1 KiB
HTML
106 lines
3.1 KiB
HTML
<html>
|
|
|
|
<head>
|
|
<title>Service Worker</title>
|
|
</head>
|
|
|
|
<body>
|
|
<script>
|
|
window.clearSW = () => {
|
|
navigator.serviceWorker.getRegistrations().then((registrations) => {
|
|
registrations.forEach((registration) => {
|
|
registration.unregister();
|
|
});
|
|
});
|
|
}
|
|
</script>
|
|
<script>
|
|
if ('serviceWorker' in navigator) {
|
|
window.addEventListener('load', () => {
|
|
navigator.serviceWorker.register('./sw.js')
|
|
.then(registration => {
|
|
console.log('Service Worker registered with scope:', registration.scope);
|
|
// 检查是否有新版本的 Service Worker
|
|
checkForNewVersion(registration);
|
|
})
|
|
.catch(error => {
|
|
console.error('Service Worker registration failed:', error);
|
|
});
|
|
});
|
|
}
|
|
|
|
function checkForNewVersion(registration) {
|
|
registration.onupdatefound = () => {
|
|
const installingWorker = registration.installing;
|
|
console.log('A new version is being installed:', installingWorker);
|
|
|
|
installingWorker.onstatechange = () => {
|
|
if (installingWorker.state === 'installed') {
|
|
if (navigator.serviceWorker.controller) {
|
|
console.log('New content is available; please refresh.');
|
|
// 显示一个提示给用户,告知他们有新版本可用
|
|
showUpdateNotification();
|
|
} else {
|
|
console.log('Content is cached for offline use.');
|
|
}
|
|
}
|
|
};
|
|
};
|
|
}
|
|
|
|
function showUpdateNotification() {
|
|
// 显示一个通知给用户,告知他们有新版本可用
|
|
if (document.hasFocus()) {
|
|
// 如果页面已经聚焦,直接显示通知
|
|
alert('New content is available; please refresh.');
|
|
window.location.reload();
|
|
} else {
|
|
// 如果页面没有聚焦,可以使用 Notification API
|
|
if (Notification.permission === 'granted') {
|
|
new Notification('New content is available; please refresh.');
|
|
} else if (Notification.permission !== 'denied') {
|
|
Notification.requestPermission().then(permission => {
|
|
if (permission === 'granted') {
|
|
new Notification('New content is available; please refresh.');
|
|
}
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
</script>
|
|
<script>
|
|
// fetch('/api/s1/sw/js/123.js')
|
|
// .then(res => res.text())
|
|
// .then(text => {
|
|
// console.log('text', text);
|
|
// });
|
|
// fetch('/api/s1/sw/js/123.js', {
|
|
// method: 'POST',
|
|
// body: JSON.stringify({
|
|
// a: 1,
|
|
// }),
|
|
// })
|
|
// .then(res => res.text())
|
|
// .then(text => {
|
|
// console.log('text', text);
|
|
// });
|
|
</script>
|
|
<script type="module">
|
|
const url = new URL('/api/s1/sw/js/123.js', window.location.origin);
|
|
import(url).then(res => {
|
|
console.log('res', res);
|
|
});
|
|
// import(url).then(res => {
|
|
// console.log('res2', res);
|
|
// });
|
|
fetch(url).then(res => {
|
|
console.log('res3', res);
|
|
});
|
|
fetch(url).then(res => {
|
|
console.log('res4', res);
|
|
});
|
|
</script>
|
|
</body>
|
|
|
|
</html> |