65 lines
2.3 KiB
JavaScript
65 lines
2.3 KiB
JavaScript
// 导出数据
|
|
document.getElementById('export').addEventListener('click', async () => {
|
|
const { aliases } = await chrome.storage.local.get('aliases');
|
|
const blob = new Blob([JSON.stringify(aliases || {}, null, 2)], { type: 'application/json' });
|
|
const url = URL.createObjectURL(blob);
|
|
|
|
const timestamp = new Date()
|
|
.toLocaleString('sv-SE') // ISO-like 格式
|
|
.replace(' ', '_')
|
|
.replace(/:/g, '-'); // 避免非法文件名
|
|
|
|
const a = document.createElement('a');
|
|
a.href = url;
|
|
a.download = `teams-alias-${timestamp}.json`;
|
|
a.click();
|
|
|
|
URL.revokeObjectURL(url);
|
|
});
|
|
|
|
// 通用导入处理函数
|
|
function handleFileImport(mode = 'overwrite') {
|
|
const fileInput = document.getElementById('fileInput');
|
|
|
|
const handler = async (e) => {
|
|
const file = e.target.files[0];
|
|
if (!file) return;
|
|
|
|
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'));
|