0

I am having issues preventing the browser from creating emojis inside of 'textarea' and 'input' elements, by triggering shortcuts like 'alt + 1', 'alt + 2'.

This code prohibits any interaction with said elements, but 'alt + 1' still creates smileys. Tested on Chrome and Edge. Am I missing something?

'use strict';
(() => {
  document.onkeydown = document.onkeypress = document.onkeyup = ev => {
    ev.stopPropagation();
    ev.preventDefault();
    return false;
  }
})();

https://jsfiddle.net/9Lr0hays/1/

Note: I don't want to interact with the elements directly (using selectors).

I am talking about these symbols: http://www.alt-codes.net/

Related: Disable Alt Codes/Characters with JavaScript

Community
  • 1
  • 1
Christoph Bühler
  • 2,795
  • 2
  • 28
  • 43

2 Answers2

1

One possible solution to this problem is check key codes.

<input type="text" id="number" onkeypress="return iskey(event);" />
<script>
function iskey(evt) {
    var theEvent = evt || window.event;
    var theVal = theEvent.target.value;
    var key = theEvent.keyCode || theEvent.which;

    key = String.fromCharCode(key);

    if (key.length == 0) return;
        if (theEvent.preventDefault) theEvent.preventDefault();
        return false;
}
</script>

Working here: https://jsfiddle.net/1569atLz/23/

XIMRX
  • 2,130
  • 3
  • 29
  • 60
0

Very bad mistake. I wrote document.keypress instead of document.onkeypress in the fiddle (the snippet was correct).

Working solution:

'use strict';
(() => {
  document.onkeypress = ev => false;
})();

https://jsfiddle.net/9Lr0hays/3/

Christoph Bühler
  • 2,795
  • 2
  • 28
  • 43