The modern way
Using the Async Clipboard API
To read text from the user's clipboard programmatically, for example, after a button click, you can use the readText()
method of the Async Clipboard API. If permissions to read clipboard have not been granted yet, the call to navigator.clipboard.readText()
will request it upon the first call to the method.
const pasteButton = document.querySelector('#paste-button');
pasteButton.addEventListener('click', async () => {
try {
const text = await navigator.clipboard.readText()
document.querySelector('textarea').value += text;
console.log('Text pasted.');
} catch (error) {
console.log('Failed to read clipboard');
}
});
The classic way
Using document.execCommand()
By using the document.execCommand('paste')
you can paste the clipboard content at the insertion point (currently focused HTML element). The execCommand
method returns a boolean that indicates whether the paste
event was successful. However this method comes with limitations, for example because it's synchronous, pasting large amounts of data can block the page.
pasteButton.addEventListener('click', () => {
document.querySelector('textarea').focus();
const result = document.execCommand('paste')
console.log('document.execCommand result: ', result);
})
Progressive enhancement
pasteButton.addEventListener('click', async () => {
try {
const text = await navigator.clipboard.readText()
document.querySelector('textarea').value += text;
console.log('Text pasted.');
} catch (error) {
console.log('Failed to read clipboard. Using execCommand instead.');
document.querySelector('textarea').focus();
const result = document.execCommand('paste')
console.log('document.execCommand result: ', result);
}
});
Further reading
Demo
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link
rel="icon"
href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2290%22>🎉</text></svg>"
/>
<title>How to paste text</title>
</head>
<body>
<h1>How to paste text</h1>
<p>
<button type="button">Paste</button>
</p>
<textarea></textarea>
</body>
</html>
CSS
:root {
color-scheme: dark light;
}
html {
box-sizing: border-box;
}
*,
*:before,
*:after {
box-sizing: inherit;
}
body {
margin: 1rem;
font-family: system-ui, sans-serif;
}
button {
display: block;
}
JS
const pasteButton = document.querySelector('button');
pasteButton.addEventListener('click', async () => {
try {
const text = await navigator.clipboard.readText()
document.querySelector('textarea').value += text;
console.log('Text pasted.');
} catch (error) {
console.log('Failed to read clipboard. Using execCommand instead.');
document.querySelector('textarea').focus();
const result = document.execCommand('paste')
console.log('document.execCommand result: ', result);
}
});