参考:
https://cloud.tencent.com/developer/article/2322236
todlist网页参考:
https://blog.csdn.net/weixin_42357472/article/details/140657576
实现在线网页当成app应用:
一个 PWA 应用首先是一个网页, 是通过 Web 技术编写出的一个网页应用,随后通过App Shell 架构添加上 Manifest 实现添加至设备主屏幕, 在通过 Service Worker 来实现离线缓存和消息推送等功能。
创建项目
目录结构
manifest.json
{
"name": "TodoList",
"short_name": "TodoList",
"description": "A simple todo list application",
"start_url": "/index.html",
"display": "standalone",
"background_color": "#ffffff",
"theme_color": "#4CAF50",
"icons": [
{
"src": "icon-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "icon-512x512.png",
"sizes": "512x512",
"type": "image/png"
}
]
}
service-worker.js
本地测试修改
const CACHE_NAME = 'todolist-cache-v1';
const urlsToCache = [
'./',
'index.html',
'styles.css',
'script.js',
'icon-192x192.png',
'icon-512x512.png'
];
self.addEventListener('install', event => {
event.waitUntil(
caches.open(CACHE_NAME)
.then(cache => cache.addAll(urlsToCache))
);
});
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request)
.then(response => response || fetch(event.request))
);
});
index.html
引入
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TodoList</title>
<link rel="stylesheet" href="styles.css">
<link rel="manifest" href="/manifest.json">
<meta name="theme-color" content="#4CAF50">
</head>
<body>
<h1>TodoList</h1>
<form id="todo-form">
<input type="text" id="todo-input" placeholder="Enter a new task" required>
<button type="submit" id="add-button">Add</button>
</form>
<ul id="todo-list"></ul>
<script src="script.js"></script>
</body>
</html>
styles.css
body {
font-family: Arial, sans-serif;
max-width: 500px;
margin: 0 auto;
padding: 20px;
}
h1 {
text-align: center;
}
#todo-form {
display: flex;
margin-bottom: 20px;
}
#todo-input {
flex-grow: 1;
padding: 10px;
font-size: 16px;
border: 1px solid #ddd;
border-radius: 4px 0 0 4px;
}
#add-button {
padding: 10px 20px;
font-size: 16px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 0 4px 4px 0;
cursor: pointer;
}
#todo-list {
list-style-type: none;
padding: 0;
}
.todo-item {
display: flex;
align-items: center;
padding: 10px;
background-color: #f9f9f9;
border: 1px solid #ddd;
margin-bottom: 10px;
border-radius: 4px;
}
.todo-item.completed {
text-decoration: line-through;
opacity: 0.6;
}
.todo-item input[type="checkbox"] {
margin-right: 10px;
}
.delete-button {
margin-left: auto;
background-color: #f44336;
color: white;
border: none;
padding: 5px 10px;
border-radius: 4px;
cursor: pointer;
}
script.js
const todoForm = document.getElementById('todo-form');
const todoInput = document.getElementById('todo-input');
const todoList = document.getElementById('todo-list');
function loadTodos() {
const todos = JSON.parse(localStorage.getItem('todos')) || [];
todos.forEach(todo => {
addTodoToDOM(todo.text, todo.completed);
});
}
function saveTodos() {
const todos = Array.from(todoList.children).map(li => ({
text: li.querySelector('span').textContent,
completed: li.classList.contains('completed')
}));
localStorage.setItem('todos', JSON.stringify(todos));
}
function addTodoToDOM(text, completed = false) {
const li = document.createElement('li');
li.className = 'todo-item' + (completed ? ' completed' : '');
li.innerHTML = `
<input type="checkbox" ${completed ? 'checked' : ''}>
<span>${text}</span>
<button class="delete-button">Delete</button>
`;
li.querySelector('input[type="checkbox"]').addEventListener('change', function() {
li.classList.toggle('completed');
if (li.classList.contains('completed')) {
todoList.appendChild(li);
} else {
todoList.insertBefore(li, todoList.firstChild);
}
saveTodos();
});
li.querySelector('.delete-button').addEventListener('click', function() {
li.remove();
saveTodos();
});
if (completed) {
todoList.appendChild(li);
} else {
todoList.insertBefore(li, todoList.firstChild);
}
}
todoForm.addEventListener('submit', function(e) {
e.preventDefault();
if (todoInput.value.trim() === '') return;
addTodoToDOM(todoInput.value);
saveTodos();
todoInput.value = '';
});
loadTodos();
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/service-worker.js')
.then(registration => {
console.log('Service Worker registered successfully:', registration.scope);
})
.catch(error => {
console.log('Service Worker registration failed:', error);
});
});
}
部署测试
PWA要求必须通过HTTPS提供服务。这里用python直接起个http服务
cd pwa-todolist
python -m http.server 8000
打开网页:
http://localhost:8000/index.html
点击右上角安装按钮可以弹出安装
安装好后弹出应用窗口,同时桌面也生成个快捷方式:
右上角可以再次返回浏览器打开和卸载应用:
然后现在关闭python -m http.server 8000服务或关闭整个浏览器
再次打开浏览器输入http://localhost:8000/,页面依旧存在