generated at
scrapbox-keyboard-emulation
JSからscrapboxをキーボード操作するためのlow-level script

ポイント
dispatchEventを使う
KeyboardEvent.keyCodeに値を渡す

script.js
const KEYCODE_MAP = { Backspace:8, Tab: 9, Enter: 13, Delete: 46, Escape: 27, ' ': 32, PageUp: 33, PageDown: 34, End: 35, Home: 36, ArrowLeft: 37, ArrowUp: 38, ArrowRight: 39, ArrowDown: 40, a: 65, b: 66, c: 67, d: 68, e: 69, f: 70, g: 71, h: 72, i: 73, j: 74, k: 75, l: 76, m: 77, n: 78, o: 79, p: 80, q: 81, r: 82, s: 83, t: 84, u: 85, v: 86, w: 87, x: 88, y: 89, z: 90, F5: 116, F12: 123, '[': 219, }; import {scrapboxDOM} from '/api/code/programming-notes/scrapbox-dom-accessor/script.js'; export function press(key, {shiftKey = false, ctrlKey = false, altKey = false, noKey = false} = {}) { // 大文字キーの場合は小文字にする const lowerKey = key.length === 1 ? key.toLowerCase() : key; if (!KEYCODE_MAP[lowerKey]) { throw Error(`No key code of ${key}`); } const options = { bubbles: true, cancelable: true, keyCode: KEYCODE_MAP[lowerKey], shiftKey: shiftKey, ctrlKey: ctrlKey, altKey: altKey, }; scrapboxDOM.textInput.dispatchEvent(new KeyboardEvent('keydown', options)); scrapboxDOM.textInput.dispatchEvent(new KeyboardEvent('keyup', options)); }