Home > Software engineering >  Is it possible to fully disable text selection for input?(Bugged user-select in input element (Chrom
Is it possible to fully disable text selection for input?(Bugged user-select in input element (Chrom

Time:08-28

I've been trying to find a way to fully prevent text input text selection (Chrome, v. 104)

#testInput {
  user-select: none;
  pointer-events: none;
  width: 100%;
}
<!DOCTYPE HTML>
<html>
  <label for="testInput">Input label</label>
  <input id="testInput" type="text" value="Test value">
</html>

It is still possible to select text inside the input. Either through selecting the end of the label text and dragging mouse through the input, control a and other ways. user-select also seems to have no effect on input element, the only reason copying directly is impossible is due to the pointer-events: none css setting.

https://jsfiddle.net/a69bswmq/

CodePudding user response:

Although it's possible for someone to look at the source code and copy the text, here are some JS hacks that will make the copying a little bit harder and prevent non-developers to copy the text:

document.getElementById('testInput')
.addEventListener('selectionchange ', function (e) {
  window.getSelection().empty();
  window.getSelection().removeAllRanges();
});

// Detect Ctrl/Cmd C and temporarily switch the value
document.addEventListener("keydown", e =>{
  const input = document.getElementById('testInput');
  const oldVal = input.value;
  if ( (e.ctrlKey || e.metaKey ) && ( e.key === "c" || e.code === "KeyC") ){
    input.value = "DON'T COPY";
    setTimeout(()=>{
      input.value = oldVal;
    }, 1000)
  }
})

// Disable Right-Click and Copy
document.addEventListener("contextmenu", e =>{
    const selection = window.getSelection();
    if ( selection && ( selection.type === 'Range' ) ){
      e.preventDefault();
    }
})
#testInput {
  user-select: none;
  pointer-events: none;
  width: 100%;
}
<label for="testInput">Input label</label>
<input id="testInput" type="text" value="Test value">

This is just a simple example to get you started. We can track other events also (drag, selection, mousedown, etc.) and make this even harder for someone to copy the text ...unless they open the DevTools and take a peek at the input value. ¯_(ツ)_/¯

Another approach would be to super-impose another element on top of the input element so that when the user tried to copy the text, they would be interacting with another element instead of the input element containing the value.

CodePudding user response:

Just use the "disabled" attribute.

<input id="testInput" type="text" value="Test value" disabled>
  • Related