Home  >  Article  >  Web Front-end  >  How to Correctly Simulate Keydown Events in Chrome?

How to Correctly Simulate Keydown Events in Chrome?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-18 13:22:02470browse

How to Correctly Simulate Keydown Events in Chrome?

Keydown Simulation in Chrome: Correctly Setting the Key Pressed

Problem Description

Simulating keydown events on a textarea in Chrome using initKeyboardEvent results in the wrong key being typed. Setting keyCode explicitly fails to resolve the issue.

Solution

The key to successfully simulating keydown events lies in overriding not only the keyCode property but also the which property, as demonstrated below:

<code class="js">document.addEventListener('keydown', e => console.log(
  'altKey                : ' + e.altKey + '\n' +
  'charCode (Deprecated) : ' + e.charCode + '\n' +
  'code                  : ' + e.code + '\n' +
  'ctrlKey               : ' + e.ctrlKey + '\n' +
  'isComposing           : ' + e.isComposing + '\n' +
  'key                   : ' + e.key + '\n' +
  'keyCode (Deprecated)  : ' + e.keyCode + '\n' +
  'location              : ' + e.location + '\n' +
  'metaKey               : ' + e.metaKey + '\n' +
  'repeat                : ' + e.repeat + '\n' +
  'shiftKey              : ' + e.shiftKey + '\n' +
  'which (Deprecated)    : ' + e.which + '\n' +
  'isTrusted             : ' + e.isTrusted + '\n' +
  'type                  : ' + e.type
));

Podium = {};
Podium.keydown = function(k) {
  var oEvent = document.createEvent('KeyboardEvent');

  // Chromium Hack
  Object.defineProperty(
    oEvent,
    'keyCode',
    {
       get : function() {
         return this.keyCodeVal;
       }
    }
  );
  Object.defineProperty(
    oEvent,
    'which',
    {
       get : function() {
         return this.keyCodeVal;
       }
    }
  );

  if (oEvent.initKeyboardEvent) {
    oEvent.initKeyboardEvent("keydown", true, true, document.defaultView,
                             false, false, false, false, k, k);
  }
  else {
      oEvent.initKeyEvent("keydown", true, true, document.defaultView,
                          false, false, false, false, k, 0);
  }

  oEvent.keyCodeVal = k;

  if (oEvent.keyCode !== k) {
    alert("keyCode mismatch " + oEvent.keyCode + "(" + oEvent.which + ")");
  }

  document.dispatchEvent(oEvent);
}

//Sample usage
Podium.keydown(65);</code>

The above is the detailed content of How to Correctly Simulate Keydown Events in Chrome?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn