HOWTO · JavaScript
在 JavaScript 中模擬按鍵
本教程幫助你使用 JavaScript 以程式設計方式模擬按鍵。
本頁內容
網頁應用程式經常需要回應鍵盤輸入,而測試這種行為通常代表要手動按鍵。JavaScript 可以改為建立合成的 KeyboardEvent 並將其傳遞給元素,讓腳本觸發與實際按鍵相同的監聽器。本文說明如何建構與派送這些事件、監聽器如何觀察它們,以及這種模擬在哪些方面仍不同於真實使用者輸入。
合成鍵盤事件的運作方式
當使用者按下按鍵時,瀏覽器會產生一系列受信任事件:按鍵按下時產生 keydown,產生字元的按鍵產生 keypress(現已棄用),放開按鍵時產生 keyup。腳本無法重現這種實體輸入,但可以建構等效的事件物件,並讓它走相同的派送路徑。
需要兩個要素:
KeyboardEvent建構函式會建立一個屬性可描述此次按鍵的事件:key保存字元值,例如"a"或"Enter";code識別實體按鍵,例如"KeyA";而ctrlKey、shiftKey、altKey和metaKey旗標則描述按住哪些修飾鍵。dispatchEvent會將事件傳遞給目標元素。監聽器會立即執行——派送是同步的——而且當事件以bubbles: true建立時,它會沿著祖先元素繼續向上傳到document和window。
作為對照,以下是實際按下 a 鍵所產生的 keypress 事件在瀏覽器主控台中展開後的樣子:isTrusted 為 true,而 key、code、charCode、keyCode 和 which 保存的值,與腳本透過初始化物件指定的值相同。
相反地,以這種方式派送的每個事件,其 isTrusted 都會是 false,藉此與真實使用者輸入區分。最後一節會說明這項差異在實務上的意義。
建立並派送 KeyboardEvent
建構函式接受事件類型以及可選的初始化物件:new KeyboardEvent(type, init)。使用 "keydown" 或 "keyup" 作為類型;keypress 為了相容性仍然存在,但已棄用,因此新的監聽器應綁定到 keydown。初始化物件會設定監聽器將讀取的屬性。
建構完成後,使用 target.dispatchEvent(event) 傳送事件。請在派送前註冊監聽器——之後新增的監聽器絕對看不到已經傳遞的事件。
在頁面上,監聽器通常綁定到 window 或某個元素,而事件則在 document.body 上派送;搭配 bubbles: true 時,事件會沿著祖先鏈向上傳,因此 window 監聽器仍會觸發:
本節中的程式碼以及顯示的標籤或輸出仍為英文。
<!DOCTYPE html>
<html>
<body>
<script>
// Register the listener first; dispatchEvent runs listeners synchronously.
window.addEventListener("keydown", function (event) {
if (event.key === "a") {
console.log(event);
}
});
// Build a synthetic keydown event for the "a" key.
const keyEvent = new KeyboardEvent("keydown", {
key: "a", // value a listener reads as event.key
code: "KeyA", // physical key position
keyCode: 97, // deprecated; only for legacy listeners
charCode: 97, // deprecated; only for legacy listeners
bubbles: true,
cancelable: true
});
// Deliver the event; the window listener receives it as it bubbles up.
document.body.dispatchEvent(keyEvent);
</script>
</body>
</html>
因為 bubbles 設為 true,即使事件是在 document.body 上派送,綁定到 window 的監聽器仍會觸發。監聽器會記錄整個 KeyboardEvent 物件;在主控台中展開它會看到 type: "keydown"、isTrusted: false、key: "a"、code: "KeyA",以及舊版 charCode 和 keyCode 值 97。
相同的建構與派送模式也能在瀏覽器外執行,方便快速檢查監聽器。Node.js 沒有 DOM KeyboardEvent,因此下方腳本只會在尚未提供這個類別時定義等效類別——在真實頁面中會改用內建類別——並在一般的 EventTarget 上派送;EventTarget 提供與 DOM 元素相同的 addEventListener/dispatchEvent 介面。
執行這個範例:
// The DOM defines KeyboardEvent; Node does not, so this stand-in supplies
// the same fields when the script runs outside a browser.
if (typeof KeyboardEvent === "undefined") {
globalThis.KeyboardEvent = class extends Event {
constructor(type, init = {}) {
super(type, init);
this.key = init.key;
this.code = init.code;
this.ctrlKey = Boolean(init.ctrlKey);
this.shiftKey = Boolean(init.shiftKey);
this.altKey = Boolean(init.altKey);
this.metaKey = Boolean(init.metaKey);
}
};
}
const target = new EventTarget(); // stands in for a DOM element
// Register the listener first; dispatchEvent runs listeners synchronously.
target.addEventListener("keydown", function (event) {
if (event.key === "a") {
console.log(`keydown observed: key=${event.key} code=${event.code}`);
}
});
// Build and dispatch a synthetic keydown event for the "a" key.
const keyEvent = new KeyboardEvent("keydown", {
key: "a", // value a listener reads as event.key
code: "KeyA", // physical key position
bubbles: true,
cancelable: true
});
target.dispatchEvent(keyEvent);
keydown observed: key=a code=KeyA
獨立的 EventTarget 沒有祖先,因此 bubbles 在這裡沒有可見效果;在頁面上,它正是讓事件向上傳到 document 和 window 的旗標。
處理輸入框上的鍵盤事件
常見任務是確認欄位本身的處理常式會回應鍵盤輸入。下方頁面有一個文字輸入框和一個按鈕;點擊按鈕會建立 keydown 事件並直接在輸入框上派送,因此只有綁定到該輸入框(或透過事件冒泡綁定到其祖先)的監聽器會觀察到它。
本節中的程式碼以及顯示的標籤或輸出仍為英文。
<!DOCTYPE html>
<html>
<head>
<title>Simulate Keypress Example</title>
</head>
<body>
<input type="text" id="textInput" placeholder="Input field">
<button id="simulateButton">Simulate Keypress</button>
<script>
const input = document.getElementById("textInput");
// The input's own listener observes the dispatched event.
input.addEventListener("keydown", function (event) {
if (event.key === "a") {
console.log("Keypress simulated: ", event.key);
}
});
// Clicking the button creates and dispatches the event.
document.getElementById("simulateButton").addEventListener("click", function () {
const keyEvent = new KeyboardEvent("keydown", {
key: "a",
code: "KeyA",
bubbles: true,
cancelable: true
});
input.dispatchEvent(keyEvent);
});
</script>
</body>
</html>
儲存檔案,在瀏覽器中開啟,然後點擊按鈕。主控台會從輸入框的監聽器記錄 Keypress simulated: a:
請注意,派送事件只會通知監聽器——它不會把 a 放進欄位。合成的 keydown 絕不會變更 input.value;上方欄位中可見的字元是為了截圖而輸入的。若要透過腳本填入欄位,請直接指派 input.value。
模擬修飾鍵
像 Ctrl+A 這類組合,就只是設定了修飾旗標的 keydown。先為主要按鍵設定 key 和 code,再為每個按住的修飾鍵加入布林旗標——ctrlKey、shiftKey、altKey 或 metaKey(metaKey 在 macOS 上是 Command 鍵,在其他系統上是 Windows 鍵)。監聽器接著會檢查這些相同屬性。此腳本使用與先前範例相同的 KeyboardEvent 替代類別,並在一般的 EventTarget 上派送。
執行這個範例:
本節中的程式碼以及顯示的標籤或輸出仍為英文。
// Same stand-in as the first example so this script also runs where no
// DOM KeyboardEvent exists; in a browser the built-in class is used.
if (typeof KeyboardEvent === "undefined") {
globalThis.KeyboardEvent = class extends Event {
constructor(type, init = {}) {
super(type, init);
this.key = init.key;
this.code = init.code;
this.ctrlKey = Boolean(init.ctrlKey);
this.shiftKey = Boolean(init.shiftKey);
this.altKey = Boolean(init.altKey);
this.metaKey = Boolean(init.metaKey);
}
};
}
const target = new EventTarget();
// Listen for the combination on keydown.
target.addEventListener("keydown", function (event) {
if (event.ctrlKey && event.key === "a") {
console.log("Ctrl+A keypress simulated");
}
});
const event = new KeyboardEvent("keydown", {
key: "a",
code: "KeyA",
ctrlKey: true, // marks Ctrl as held during this event
bubbles: true,
cancelable: true
});
target.dispatchEvent(event);
Ctrl+A keypress simulated
在真實頁面中,相同的監聽器與建構程式碼會針對內建的 KeyboardEvent 執行;將監聽器綁定到 window,或在 document.body 上派送事件,即可讓事件觸及整個文件。主控台會顯示監聽器的訊息:
如果受測程式碼會追蹤完整的按下再放開程序,之後請再派送相符的 keyup 事件,讓序列的兩半都能被觀察到。
了解合成事件的限制
合成事件很適合測試你自己的處理常式,但不能替代真實輸入:
event.isTrusted為false,所以監聽器一律能分辨派送事件與真正的按鍵,而瀏覽器也不會讓不受信任的事件執行特權行為。- 在輸入框上派送
keydown或keyup絕不會變更其value、移動插入點,或產生beforeinput/input事件——不會輸入任何文字。 - 由鍵盤觸發的瀏覽器動作不會因不受信任的按鍵事件而執行:Ctrl+A 不會全選,Tab 不會移動焦點,F5 也不會重新載入頁面。其他啟動行為仍可能針對部分合成事件執行;例如,派送的點擊可以切換核取方塊或觸發連結。
keypress事件類型以及數值屬性keyCode/charCode/which已棄用;請優先使用搭配key和code的keydown/keyup。
對於單元測試和鬆耦合的應用程式邏輯,建構 KeyboardEvent 並呼叫 dispatchEvent 就已足夠。當你需要瀏覽器表現得就像使用者真的輸入一樣——受信任的輸入、真實的焦點變更和預設動作——請改用 Playwright、Puppeteer 或 WebDriver 這類自動化工具來驅動它。