Today I Learned - Rocky Kev

TIL about the Clipboard API

POSTED ON:

TAGS:

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.

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>

MDN

More info via StackOverflow Answer

via JavaScript 101: Accessing the Clipboard


Related TILs

Tagged:

TIL what is npm Script

Despite their high usage they are not particularly well optimized and add about 400ms of overhead. In this article we were able to bring that down to ~22ms.

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL how to hide your JS code

ONE THING TO NOTE: Encrypting a script is stronger than obfuscation, both methods are still not adequate to protect secret content. Honestly, I don't think it's worth it on a production site, and instead just go with pure server-side if you want security. But it's fascinating.