Home > Software engineering >  Javscript listen keyboard, on text input
Javscript listen keyboard, on text input

Time:12-20

I want to show popup if user input text no matter where on website, I see that javascript have key listener but what is the best way if I want to show popup when user write "ShowMePopup"?

I have write this script for test

window.addEventListener("keydown", function (event) {
  if (event.defaultPrevented) {
    return; 
  }
  
  var name = event.key;
  var code = event.code;

  console.log(`Key pressed ${name} \r\n Key code value: ${code}`);

  switch (event.key) {
    case "ArrowDown":
      alert('arrow down')
      break;
    case "Shift   S   h   o   w   Shift   M   e   Shift   P   o   p   u   p":
      alert('Secret Popup')
      break;
    default:
      return;
  }

  event.preventDefault();
}, true);


I have try to add case with

case "Shift   S   h   o   w   Shift   M   e   Shift   P   o   p   u   p":

but it wont work, any ideas?

CodePudding user response:

When a key is pressed, push it into an array. Then, check the last 11 items (the length of the desired key combo) in the array for your key combination:

const keysPressed = [];
const popupKeyCombo = ['Shift', 'S', 'h', 'o', 'w', 'Shift', 'M', 'e', 'Shift', 'P', 'o', 'p', 'u', 'p'];
window.addEventListener("keydown", e => {
    keysPressed.push(e.key);
    if(keysPressed.slice(-popupKeyCombo.length).join() === popupKeyCombo.join()){
        alert('Secret Popup');
    }
});

And consider adding additional logic to keep the array at a reasonable size.

CodePudding user response:

You can solve the issue by creating a storage variable outside of your listener function and store each key event inside of it. However, be careful with the timing of keypresses since holding shift longer, multiple key events will be fired. But with this you should make it work.

let storage = "";

window.addEventListener("keydown", function (event) {
  if (event.defaultPrevented) {
    return; 
  }
  storage  = event.key;
  console.log(storage);
  
  if(storage.includes("ShiftShowShiftMeShiftPopup")){
  alert("Surprise");
  storage = "";
  }
  event.preventDefault();
}, true);

CodePudding user response:

You may keep track of what was typed in each occurence of the keydown event and then do a substraction between the expected text and what was captured so far.

As soon as the capture diverges from what's expected, the captured string will be reset.

At each character typed, the demo will print on console the full string expected, what was captured so far since the latest reset and what's still missing.

When the passphares will be catched correctly, the function secretUnlocked gets triggered.

This solution won't have a infinitely growing buffer but just the captured string as long as it was matching the expected input. As soon as the typed string diverges, the buffer gets reset and the minimum amount of memory gets used.

let captured = "";
let expected = "ShowMePopup";


//substracts captured to expected and returns the text fragment still missing
function diff(expected, capture){
 const split = expected.split(capture);
 if(split[0].length > 0 || split.length > 2)
  return expected;
 else
  return split[1];
}

document.addEventListener('keydown', function(event) {  

  //character allowed (this is a lazy trick to exclude special keys like shift, ctrl...)
  const allowedChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';  
  if(!allowedChars.split('').includes(event.key)){  
    return;
  }
  
  //appends the latest typed char to the captured string
  captured  = event.key;    
  const stillExpecting = diff(expected, captured);

  //if stillExpecting is still the same as expected, resets the captured part
  if(stillExpecting === expected)
    captured = '';
  
  console.log(`expecting: ${expected} .. so far: ${captured} .. still expecting: ${stillExpecting}`);
  
  //if stillExpecting has zero length, the condition is met
  if (stillExpecting.length === 0){
    secretUnlocked();
  }
});

function secretUnlocked(){
  console.log('Secret Unlocked');
}
Type the secret passphrase while the document has focus...

CodePudding user response:

Wow, what a lot of code.

This one works too

let text = "";
const phrase = "ShowMePopup";
window.addEventListener("keydown", e => {
  const key = event.key;
  if (key.length !==1) return; // ignore shift etc. The shifted char is in the next key
  text  = key;
  if (text.indexOf(phrase) != -1) {
    console.log("Show popup");
    text = ""; // to handle ShowMePopupShow....
  }  
  else if (phrase.indexOf(key) === -1) text = ""; //reset
});

CodePudding user response:

You mean a key.detector with a popup like this ?. Try this code.

function showKC(event) {
var x = event.keyCode;
var y = event.key;
document.getElementById("charcode").innerHTML = "Key: " y " Code: " x;
}

function CheckPop() {
    var smp = "ShowMePopup";
    var text = document.getElementById("t1");
    if (text.value == smp) {
    alert(smp);
    }

}
Just type on keyboard <input type="text" id="t1" value="" onkeyup="showKC(event), CheckPop()"/>
<div id="charcode"></div>

  • Related