Joseph Miller
Joseph Miller

Reputation: 199

How to detect paste in text input area if user paste a whole text or string in it?

Note : Do not mark this as a duplicate question, sure this is not. But it is related to certain question out there.

There are click event or touch event to detect paste in the text field. But now there is a new trick to paste content in text field using mobile "swift keyboard" android keyboard. Which enables clipboard option to paste the predefined text into any input field. I tried almost every online answers and this clipboard works without detecting any event in the browser.

So help me out to solve this issue, i want to detect this certain clipboard event in the text field and block users from using it.

<textarea name="msg" placeholder="Type message here...." class="materialize-textarea" onCopy="return false" onDrag="return false" onDrop="return false" onPaste="return false" oncontextmenu="return false" onkeydown="if ((arguments[0] || window.event).ctrlKey) return false"></textarea>

Sure this blocks normal paste in desktop or mobile devices. But, it can't detect certain clipboard content paste.

I need a real solution to fix this issue.

Upvotes: 2

Views: 3272

Answers (1)

Nick Parsons
Nick Parsons

Reputation: 50639

Instead of detecting whether a paste event has occurred, you can listen for an input event on the textarea. Then by keeping track of the previous length of the string in the textbox you can see if the input has changed by more than one character.

See working example below:

window.onload = function() {
  const textarea = document.querySelector('.materialize-textarea');
  let prev_val = textarea.value;
  let prev = prev_val.length;

  textarea.addEventListener('input', function() {
    let new_len = this.value.length;
    let dif = new_len - prev;
    if (dif > 1) {
      alert("paste detected!");
      textarea.value = prev_val;
    } else {
      prev = new_len;
    }
    prev_val = this.value;
  });
}
<textarea name="msg" placeholder="Type message here...." class="materialize-textarea"></textarea>

Although, this solution does have its limitations.

Upvotes: 8

Related Questions