1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| let timer = null; let count = 1;
document.getElementById('start').onclick = async () => { const [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); if (!tab) return; const tabId = tab.id;
// --- 第一步:防錯處理,先強制斷開可能存在的舊連接 --- try { await chrome.debugger.detach({ tabId }); } catch (e) { // 如果原本沒連接,這會報錯,我們直接忽略它 }
// --- 第二步:重新附加 Debugger --- chrome.debugger.attach({ tabId }, "1.3", () => { if (chrome.runtime.lastError) { alert("啟動失敗!請檢查是否正開啟著 F12 開發者工具。如果是,請先關閉它。"); return; }
startAutomation(tabId); }); };
function startAutomation(tabId) { count = 1; updateStatus(`執行中... (第 ${count} 張)`);
// 設定 2 秒一次的循環 (2000 毫秒) timer = setInterval(() => { // 1. 模擬物理按鍵 ArrowRight (按下與放開) chrome.debugger.sendCommand({ tabId }, "Input.dispatchKeyEvent", { type: "keyDown", windowsVirtualKeyCode: 39, nativeVirtualKeyCode: 39, key: "ArrowRight" }); chrome.debugger.sendCommand({ tabId }, "Input.dispatchKeyEvent", { type: "keyUp", windowsVirtualKeyCode: 39, nativeVirtualKeyCode: 39, key: "ArrowRight" });
// 2. 延遲 500ms 截圖(給網頁一點點渲染時間) setTimeout(() => { chrome.tabs.captureVisibleTab(null, { format: "png" }, (dataUrl) => { if (dataUrl) { const fileName = `auto_shot_${String(count).padStart(3, '0')}.png`; chrome.downloads.download({ url: dataUrl, filename: fileName }); count++; updateStatus(`執行中... (第 ${count} 張)`); } }); }, 500);
}, 2000); // 這裡設定為 2000 毫秒 = 2 秒 }
document.getElementById('stop').onclick = () => { if (timer) { clearInterval(timer); chrome.tabs.query({ active: true, currentWindow: true }, ([tab]) => { if (tab) chrome.debugger.detach({ tabId: tab.id }); }); updateStatus("已停止執行"); } };
function updateStatus(msg) { document.getElementById('status').innerText = msg; }
|