How to gracefully get pasted value in paste event?

Viewed 12

I created UI where pasting text into textarea sends request to my API immediately. The problem is that paste event doesn't seem to be aware of the pasted value, unless I'm missing something. If I use event.target.value directly, it returns the value from before the pasting occured.

I used setTimeout() with 0ms and it works (but I'm not happy):

document.getElementById('my-textarea').addEventListener('paste', event => {
    setTimeout(() => {
        const contents = event.target.value;

        // fetch() using `contents`
    }, 0);
});

Is there some cleaner way?

1 Answers

According to MDN

A handler for this event can access the clipboard contents by calling getData() on the event's clipboardData property.

To override the default behavior (for example to insert some different data or a transformation of the clipboard contents) an event handler must cancel the default action using event.preventDefault(), and then insert its desired data manually.

So you can try this:

document.getElementById('my-textarea').addEventListener('paste', event => {
    event.preventDefault()
    const contents = event.clipboardData.getData('text')
});
Related