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} rn 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?
5
Answers
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.
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:
And consider adding additional logic to keep the array at a reasonable size.
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.
Wow, what a lot of code.
This one works too
You mean a key.detector with a popup like this ?. Try this code.