Electron 桌面应用主进程和渲染进程通信
FreeGuideOnline
最新
2026-07-08
我的待办
添加renderer.js 使用暴露的 API 进行交互:
const todoList = document.getElementById('todo-list')
const todoForm = document.getElementById('todo-form')
const todoInput = document.getElementById('todo-input')
// 渲染任务列表
function renderTodos(todos) {
todoList.innerHTML = '';
todos.forEach(todo => {
const li = document.createElement('li');
li.textContent = todo.text;
if (todo.completed) li.style.textDecoration = 'line-through';
li.addEventListener('click', () => {
window.todoAPI.toggleTodo(todo.id);
});
todoList.appendChild(li);
});
}
// 页面加载时获取数据
async function initApp() {
const todos = await window.todoAPI.getTodos();
renderTodos(todos);
}
// 监听主进程推送的更新
window.todoAPI.onTodosUpdated((todos) => {
renderTodos(todos);
});
// 添加新任务
todoForm.addEventListener('submit', async (e) => {
e.preventDefault();
const text = todoInput.value.trim();
if (text) {
await window.todoAPI.addTodo(text);
todoInput.value = '';
}
});
initApp();