Sometimes, we may want to get the clipboard data that we paste into an element in our web app.
In this article, we’ll look at how to get clipboard data when we paste it into our JavaScript app.
Listen to the paste Event
The paste
event is triggered when we paste data into an element.
Therefore, we can just listen to that event when our own event listener to get the pasted content.
For instance, we can write the following HTML:
<div id='editableDiv' contenteditable='true'>Paste</div>
Then we can write the following JavaScript code to listen to the paste
event:
const handlePaste = (e) => {
let clipboardData, pastedData;
e.stopPropagation();
e.preventDefault();
clipboardData = e.clipboardData || window.clipboardData;
pastedData = clipboardData.getData('text/plain');
console.log(pastedData);
}
const div = document.getElementById('editableDiv')
div.addEventListener('paste', handlePaste);
We create the handlePaste
function to get the clipboard data.
First, we call stopPropagation
to stop the propagation of the event to the parent and ancestor elements.
Then we call preventDefault
to prevent the default paste behavior.
Then we can get the clipboard data from the e.clipboardData
or window.clipboardData
properties.
Next, we call getData
with 'text/plain'
to get the pasted text data.
And then we log the pastedData
with console log.
Then we select the editable div with the getElementById
method.
And we call addEventListener
on the div to listen to the paste
event.
We can simplify the function by calling e.clipboardData.getData
to get the data directly.
Then we can call document.execCommand
to do the pasting to the div.
To do this, we write:
const handlePaste = (e) => {
const pastedText = e.clipboardData.getData('text/plain')
console.log(pastedText)
document.execCommand('insertText', false, pastedText);
e.preventDefault();
}
const div = document.getElementById('editableDiv')
div.addEventListener('paste', handlePaste);
We get the pasted text with:
e.clipboardData.getData('text/plain')
Then pastedText
has what we pasted into the div.
Then we run:
document.execCommand('insertText', false, pastedText);
to insert the text by issuing the insertText
command with the pastedText
.
The rest of the code is the same.
Conclusion
We can listen to the paste
event on an element and get the data from the event object of the paste
event handler to get the data pasted into an element.