0

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.

ash patel
  • 15
  • 3
  • Possible duplicate of [JavaScript get clipboard data on paste event (Cross browser)](https://stackoverflow.com/questions/2176861/javascript-get-clipboard-data-on-paste-event-cross-browser) – Mr. Polywhirl Mar 01 '19 at 12:52
  • @Mr.Polywhirl i had a look on that as well, but the solutions are using `event.clipboardData.getData('text');` and i want to get the individual text part. – ash patel Mar 01 '19 at 12:58

2 Answers2

1

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>
Joe Warner
  • 2,928
  • 1
  • 12
  • 29
0

Your item is of type DataTransferItem so you should use getAsString() to retrieve the text of the item;

This function takes a callback function as first argument : item.getAsString(str => console.log(str));

Adrien
  • 497
  • 4
  • 9
  • This works, but along with the copied text, it also prints out some html and rtf text – ash patel Mar 01 '19 at 13:12
  • If you want to delete those HTML tags you'll need to do further processing of the text, because HTML is treated as text. You can strip all tags with a regex like `str.replace(/]+)>/g, "")` – Adrien Mar 01 '19 at 13:21
  • I tried out using `item.type === 'text/html'` and then printing it within an html element. Now the formatting is maintained and I get the text I need. Thank you – ash patel Mar 02 '19 at 20:37