Search code examples
javascripthtmlclipboarddata

Uncaught TypeError: item.getData is not a function


I want to paste the clipboard content on html page. The content is copied from an ms-word file. Contains text and images. Consider the following code:

<div id="pasteArea" contenteditable="True"></div>
<script type="text/javascript">
    var pasteArea = document.getElementById('pasteArea');
    pasteArea.onpaste = function (event) {
        event.preventDefault();
        event.stopPropagation();
        var items = (event.clipboardData || event.originalEvent.clipboardData).items;
        for (index in items) {
            var item = items[index];
            if(item.kind === 'string'){
                console.log(item.getData('text'));
                // Getting the error in here!
            }
            else if(item.kind === 'file'){
                // Code for handling images
            }
        }
    }
</script>

I tried using event.clipboardData.getData('text'); but it fetches the entire text (i.e. skips the images in between) and also the text formatting is lost.

Any idea on how to handle the above case? Thank you.


Solution

  • You're looking for getAsString which requires a callback to process the clipboard.

    https://developer.mozilla.org/en-US/docs/Web/API/DataTransferItem/getAsString

    const pasteArea = document.getElementById('pasteArea');
    
    pasteArea.onpaste = event => {
      event.preventDefault();
    
      const { items } = event.clipboardData;
      for (const item of items) processClipboard(item)
    }
    
    const processClipboard = item => {
      if (item.kind === 'string' && item.type === 'text/plain') {
    
        item.getAsString(s => console.log(s))
    
      }
    }
    div { background-color: #ccc; }
    <div id="pasteArea" contenteditable="True">Paste something here</div>