Search code examples
javascripthtmlclipboard

JavaScript clipboardData void Text


I am using the below code to copy data from the clipboard into my form and submit. Previously this was very limited to only images on browsers, now browsers allow everything from files to text. The problem is when text is copied, it thinks its a file and wants to submit.

Is there a way to void all types of text being pasted?

const fileInput = document.getElementById("document_attachment_doc");

window.addEventListener('paste', e => {
  fileInput.files = e.clipboardData.files;
  document.getElementById("new_document_attachment").submit();
});

Solution

  • What I did find is that the form submit is triggered due to the paste even if there ae no files and just plain text. A workaround was to check that the file count in the clipboard was more than 0. If there is text in the clipboard its 0.

     window.addEventListener('paste', e => {
      if (e.clipboardData.files.length > 0){
        fileInput.files = e.clipboardData.files;
        document.getElementById("new_document_attachment").submit();
       }
     });