<!doctype html>
<meta charset=utf-8>
<head>
    <title>Test Keys</title>
    <script>
        var allEvents = {events: []};
        function displayMessage(message) {
            document.getElementById("events").innerHTML = "<p>" + message + "</p>";
        }

        function appendMessage(message) {
            document.getElementById("events").innerHTML += "<p>" + message + "</p>";
        }

        /**
         * Escape |key| if it's in a surrogate-half character range.
         *
         * Example: given "\ud83d" return "U+d83d".
         *
         * Otherwise JSON.stringify will convert it to U+FFFD (REPLACEMENT CHARACTER)
         * when returning a value from executeScript, for example.
         */
        function escapeSurrogateHalf(key) {
          if (typeof key !== "undefined" && key.length === 1) {
            var charCode = key.charCodeAt(0);
            var highSurrogate = charCode >= 0xD800 && charCode <= 0xDBFF;
            var surrogate = highSurrogate || (charCode >= 0xDC00 && charCode <= 0xDFFF);
            if (surrogate) {
              key = "U+" + charCode.toString(16);
            }
          }
          return key;
        }

        function recordEvent(event) {
          var key = escapeSurrogateHalf(event.key);
          allEvents.events.push({
            "code": event.code,
            "key": key,
            "which": event.which,
            "location": event.location,
            "ctrl": event.ctrlKey,
            "meta": event.metaKey,
            "shift": event.shiftKey,
            "repeat": event.repeat,
            "type": event.type
          });
          appendMessage(`${event.type}(code:${event.code}, key:${key}, which:${event.which})`);
        }

        function resetEvents() {
            allEvents.events.length = 0;
            displayMessage("");
        }
    </script>
</head>
<body>
  <div>
    <h2>KeyReporter</h2>
    <input type="text" id="keys" size="80"
           onkeyup="recordEvent(event)"
           onkeypress="recordEvent(event)"
           onkeydown="recordEvent(event)">
  </div>
  <div id="resultContainer" style="width:300;height:60">
    <h2>Events</h2>
    <div id="events"></div>
  </div>
</body>
