Greasy Fork is available in English.

讨论 » 创建请求

insert keyboard events on a document

§
发表于:2023-04-01

is it possible to insert keyboard events (e.x. enter key) in a userscript?

NotYou管理员
§
发表于:2023-04-02

You can't "insert" keyboard events in a user-script, but you can dispatch keyboard events to elements (nodes). There is example, how you can do that:

(function() {
  const NODE = document.querySelector('html')
  const KEY_CODE = 13
  const CODE = 'Enter'

  const IS_SHIFT_PRESSED = false
  const IS_CTRL_PRESSED = false
  const IS_ALT_PRESSED = false

  const PARAMS = Object.assign({
    target: NODE,
    keyCode: KEY_CODE,
    which: KEY_CODE,
    code: CODE,
    shiftKey: IS_SHIFT_PRESSED,
    ctrlKey: IS_CTRL_PRESSED,
    altKey: IS_ALT_PRESSED,
  }, IS_CTRL_PRESSED ? { metaKey: true } : {})

  NODE.dispatchEvent(new KeyboardEvent('keydown', PARAMS))
  NODE.dispatchEvent(new KeyboardEvent('keyup', PARAMS))
})()

To emulate f key, write KeyF and so on, also you should write ev.keyCode because some websites still use it instead of ev.code. There is a tool for that: https://www.toptal.com/developers/keycode (Copy key code and event.code text after key press)

发表回复

登录以发表回复。