Search code examples
javascriptkeyevent

Detect shift + copy keystrokes in javascript


i'd like to handle keystroke combination of shift + copy. what i am doing is checking if keystrokes shift + cmd + c are all keydown, which is effectively shift + copy.

  var keyPressed = {};
  window.addEventListener("keydown", function (e) {
    keyPressed[e.key] = true;
    const keyList = Object.keys(keyPressed);

    const isShiftCopy = ["Meta", "Shift", "c"].every((x) =>
      keyList.includes(x)
    );

    if (isShiftCopy) {
      console.log("shift copy called");
      e.preventDefault();
    }
  });

this works but it listens to every keystroke though. is there a better way?

here's what i'm doing for basic copy keystrokes.

  window.addEventListener("copy", function (e) {
      console.log("copy called");

       // TODO can shift be detected at the same time as this copy event?
    });

it'd be great to avoid listening to all possible keystrokes to detect shift + copy. can shift be detected from copy event listener? or is there another possible solution other than using keydown ?


Solution

  • The copy event does not have any keystrokes that are carried along with the event. The only way to accomplish this is to simply filter the keystrokes, as you've done in your first example.

    If you want to read more into the event object that copy has, it's a ClipboardEvent

    However, if you want the copy event to get the current selection, you can use the Selection API to help you see what text / nodes are selected when the user copies things.