diff --git a/public/migrate.html b/public/migrate.html index e7182d22..67960858 100644 --- a/public/migrate.html +++ b/public/migrate.html @@ -75,7 +75,13 @@ }, event.origin); log("已发送迁移数据"); + // 自动关闭窗口(延迟 500ms) + setTimeout(() => { + window.close(); + }, 500); }); + + diff --git a/public/static-home.html b/public/static-home.html index 355ccdd5..e0d29462 100644 --- a/public/static-home.html +++ b/public/static-home.html @@ -355,20 +355,22 @@ }); } - // 2️⃣ 创建 iframe 并发送迁移请求 + // 创建迁移窗口并接收数据 async function migrateFromOldSite() { return new Promise(async (resolve, reject) => { const db = await loadIDBKeyval(); - const iframe = document.createElement('iframe'); - iframe.style.display = 'none'; - iframe.src = `${OLD_ORIGIN}/migrate.html`; + const migrateWin = window.open(`${OLD_ORIGIN}/migrate.html`, '_blank', 'width=400,height=400'); + + if (!migrateWin) return reject('弹窗被阻止,请允许弹窗'); - // 安全接收旧域名返回的数据 function onMessage(event) { + if (event.origin !== OLD_ORIGIN) return; if (event.data?.type !== 'MIGRATION_RESULT') return; + const payload = event.data.payload; - console.log('payload',payload) + + console.log('payload', payload); // 写入 localStorage LS_KEYS.forEach(key => { @@ -385,26 +387,30 @@ } } - // 清理 window.removeEventListener('message', onMessage); - iframe.remove(); resolve(true); })(); } window.addEventListener('message', onMessage); - // 等 iframe 加载完成再发请求 - iframe.onload = () => { - setTimeout(()=>{ - iframe.contentWindow.postMessage({type: 'REQUEST_MIGRATION_DATA'}, 'https://2study.top'); - },3000) - }; - - document.body.appendChild(iframe); + // 等窗口加载完毕后发请求 + const timer = setInterval(() => { + if (!migrateWin || migrateWin.closed) { + clearInterval(timer); + reject('迁移窗口已关闭'); + } else { + try { + migrateWin.postMessage({type: 'REQUEST_MIGRATION_DATA'}, OLD_ORIGIN); + } catch (e) { + // 跨域安全错误忽略,等窗口完全加载后再试 + } + } + }, 100); }); } + if (location.href === 'https://typewords.cc/') { window.addEventListener("DOMContentLoaded", () => { // 3️⃣ 自动执行迁移(只执行一次)