1

The following userscript is not capturing the ctrlKey event.

// ==UserScript==
// @name      CtrlKey alert
// @namespace CtrlKey alert
// @include   *
// @run-at    document-start
// ==/UserScript==

document.addEventListener(
  "keydown",
  function (zEvent) {
    if (zEvent.ctrlKey) {
      zEvent.preventDefault();
      alert("CtrlKey pressed!");
    }
  },
  true
);

An identical user script can capture any other key event, though:

// ==UserScript==
// @name      Key A alert
// @namespace Key A alert
// @include   *
// @run-at      document-start
// ==/UserScript==

document.addEventListener(
  "keydown",
  function (zEvent) {
    if (zEvent.key === "a") {
      zEvent.preventDefault();
      alert("Key A pressed!");
    }
  },
  true
);

I have tried using zEvent.stopPropagation, zEvent.stopImmediatePropagation, and zEvent.preventDefault individually but they have had no effect (this is important because the ultimate goal is to override a default ctrl+letter command like ctrl+f).

I have tried substituting document.addEventListener('keydown', function(zEvent) with document.onKeydown = function(zEvent) with no results.

Everything I've read indicates that keydown or onKeydown should capture ctrlKey, yet it doesn't. Is there something specific about ctrlKey I'm missing that's preventing javascript from capturing it?

Running Firefox v105.0.1 on Windows 11

Michael M.
  • 10,486
  • 9
  • 18
  • 34
ETL
  • 188
  • 10
  • The `ctrlKey` is a modifier to a keypress. Try hitting ctrl-A and you will see that `ctrlKey` is set, but you can't detect the ctrl key by itself in JavaScript AFAIK. Example of what I mean: https://stackoverflow.com/a/16006607/2740650 – user2740650 Oct 02 '22 at 18:31
  • The code that you linked, `if (event.ctrlKey && event.key === 'z')`, is the same as what I attempted in my question. In fact, my original goal WAS to capture the "ctrl + A" combination. I saw that it was NOT being captured, and I narrowed down the issue to `event.ctrlKey` not being captured. – ETL Oct 03 '22 at 19:36
  • Oh, not the way I interpreted it. OK, then it would be simpler to add a log like `console.log(zEvent)` to the handler in the first line. It should log something for every keystroke. Please edit your question to post the output when you hit ctrl+A. Also, try omitting the last parameter to `addEventListener` where you have specified `true`. – user2740650 Oct 03 '22 at 23:03

0 Answers0