Обговорення » Creation Requests

insert keyboard events on a document

§
Опубліковано: 01.04.2023

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

NotYouMod
§
Опубліковано: 02.04.2023

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)

Опублікувати відповідь

Sign in to post a reply.