DevTools Console 執行上下文**綁定當前頁面文檔**。提交表單觸發導航 (Navigation) → 舊文檔銷毀 → 新文檔建立 → Console 上下文重置 → 所有變數、函數、事件監聽器全部消失。
// 在 Console 執行
async function batchRegister(users) {
for (const u of users) {
const resp = await fetch('/api/register', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
credentials: 'include', // 攜帶 Cookie
body: JSON.stringify(u)
});
const data = await resp.json();
console.log(u.username, data.success ? '✅' : '❌', data.msg);
await new Promise(r => setTimeout(r, 500)); // 限流
}
}
// 使用
batchRegister([
{username: 'u1', email: 'u1@x.com', password: '123'},
{username: 'u2', email: 'u2@x.com', password: '123'}
]);
autoRegister.js// ==UserScript==
// @name Persistent Auto Register
// @match https://target.com/register*
// @grant GM_xmlhttpRequest
// @run-at document-start
// ==/UserScript==
// 頁面每次載入自動執行,無需手動介入
(async function() {
if (window.location.search.includes('auto=1')) {
await doRegister();
}
})();
| 方案 | 程式碼保存 | 頁面刷新後自動執行 | 適用場景 |
|---|---|---|---|
| Console 直接輸入 | ❌ | ❌ | 臨時調試 |
| Snippets | ✅ | ❌ | 反覆調試同一邏輯 |
| fetch 替代 submit | 視方案而定 | ✅ (同頁面) | 單次批量操作 |
| Tampermonkey/擴展 | ✅ | ✅ | 長期自動化、跨會話 |
// 覆寫 form.onsubmit,攔截並改用 fetch
const form = document.querySelector('form');
form.addEventListener('submit', async (e) => {
e.preventDefault(); // 阻止預設提交導航
const formData = new FormData(form);
const resp = await fetch(form.action, {
method: 'POST',
body: formData,
credentials: 'include'
});
const result = await resp.json();
console.log('攔截提交結果:', result);
// 這裡可決定是否手動跳轉:window.location.href = '/success';
});
**Console 腳本無法跨頁面持久化是瀏覽器架構決定的**。要實現批量註冊等自動化,核心策略是:**攔截表單提交 → 改用 fetch/XHR 呼叫後端 API → 留在原頁繼續下一輪**。配合 Snippets 管理程式碼,或升級為 Tampermonkey/擴展獲得真正的自動化能力。