使用外部数据库

This commit is contained in:
Julian Freeman
2026-01-05 12:22:01 -04:00
parent 4581297dac
commit f549059e47
9 changed files with 170 additions and 78 deletions

View File

@@ -17,48 +17,26 @@ document.getElementById('export').addEventListener('click', async () => {
URL.revokeObjectURL(url);
});
// 通用导入处理函数
function handleFileImport(mode = 'overwrite') {
const fileInput = document.getElementById('fileInput');
// 手动同步
document.getElementById('sync').addEventListener('click', async () => {
const btn = document.getElementById('sync');
const originalText = btn.textContent;
btn.textContent = '同步中...';
btn.disabled = true;
const handler = async (e) => {
const file = e.target.files[0];
if (!file) return;
try {
if (typeof fetchAliasesFromDB !== 'function') {
throw new Error("utils.js not loaded properly");
}
const reader = new FileReader();
reader.onload = async function (event) {
try {
const importedData = JSON.parse(event.target.result);
if (typeof importedData !== 'object' || importedData === null) {
alert('文件格式错误');
return;
}
const { aliases: existingAliases = {} } = await chrome.storage.local.get('aliases');
const updatedAliases = (mode === 'merge')
? { ...importedData, ...existingAliases } // 保留现有的不被导入的覆盖
: importedData;
await chrome.storage.local.set({ aliases: updatedAliases });
alert(mode === 'merge' ? '导入并合并成功' : '导入成功');
} catch (err) {
alert('无法解析 JSON 文件');
} finally {
fileInput.removeEventListener('change', handler);
fileInput.value = ''; // 重置 input 以便后续重复导入同一文件
}
};
reader.readAsText(file);
};
fileInput.addEventListener('change', handler, { once: true });
fileInput.click();
}
// 导入(覆盖)
document.getElementById('import').addEventListener('click', () => handleFileImport('overwrite'));
// 更新导入(合并)
document.getElementById('update-import').addEventListener('click', () => handleFileImport('merge'));
const aliases = await fetchAliasesFromDB();
await chrome.storage.local.set({ aliases, lastSync: Date.now() });
alert(`同步成功!共获取 ${Object.keys(aliases).length} 条数据。`);
} catch (error) {
alert('同步失败,请检查网络或控制台日志。');
console.error(error);
} finally {
btn.textContent = originalText;
btn.disabled = false;
}
});