Javascript Copy and Paste Functionality
This is an example of how to handle images or text copied in to a browser page.
With the following HTML - with placeholders for pasted images and a “Clear images” button:
<button type="button" class="buttonesque clear-logs">Clear images</button>
<p
contenteditable="true"
onpaste="console.log('something was pasted')"
style="border-radius: 3px; border: 2px solid #222; padding: 6px; margin: 3px;"
>Try to paste one or more images or some text into this paragraph.</p>
<p><strong id="log-name"></strong></p>
<ul id="log-box"> </ul>
<button type="button" class="buttonesque clear-logs">Clear images</button>
and some accompanying Javascript:
<script>
window.addEventListener('load', e => {
document.body.addEventListener('paste', e => {
e.preventDefault()
const items = e.clipboardData.items
console.log(87, items, items.length)
for (let i = 0; i < items.length; ++i) {
console.log(70, i, items[i].type, items[i].kind)
items[i].getAsString(s => console.log(71, s))
if ( items[i].kind == 'file'
&& items[i].type.indexOf('image/') !== -1
) {
const blob = items[i].getAsFile()
window.URL = window.URL || window.webkitURL
const blobUrl = window.URL.createObjectURL(blob)
const img = document.createElement('img')
img.src = blobUrl
const logBox = document.getElementById('log-box')
logBox.appendChild(img)
}
}
})
const btnArr = document.querySelectorAll('.clear-logs')
Array.from(btnArr).map(e => e.addEventListener('click', e => clearLog()))
})
function clearLog() {
const node = document.getElementById('log-box')
while (node.firstChild) {
node.removeChild(node.firstChild)
}
}
</script>
An event listener on document.body
handles a paste event and appends to the <ul>
tag
any images (files) pasted in to the <p contenteditable="true">
tag.
Demo:
Try to paste one or more images or some text into this paragraph.