TIL about the Clipboard API
POSTED ON:
TAGS: javascript mdn webapi
The Clipboard API can be used to implement cut, copy, and paste features within a web application.
Most other modern browsers have access to the navigator.clipboard
global object, which is how you’d want to interact with the clipboard in modern web applications.
-
text content, using
navigator.clipboard.readText()
andnavigator.clipboard.writeText()
. -
images, rich text, HTML, and other rich content, using
navigator.clipboard.read()
andnavigator.clipboard.write()
.
You do have to wrap it in a promise.
<html>
<head>
<script >
async function copyText() {
let textArea = document.getElementById("myText")
const permission = await navigator.permissions.query({ name: 'clipboard-read' });
if (permission.state === 'denied') {
return console.error("Damn, we don't have permissions to do this")
}
try {
await navigator.clipboard.writeText(textArea.value)
console.log("done!")
} catch (e) {
console.error("Error while copying text!")
console.error(e.message)
}
}
</script>
</head>
<body>
<textarea rows="5" cols="89" id="myText"></textarea>
<button onclick="copyText()">Share!</button>
</body>
</html>
More info via StackOverflow Answer
via JavaScript 101: Accessing the Clipboard
Related TILs
Tagged: javascript