Introduction
In this lab, we will explore the Clipboard API in JavaScript and learn how to copy text asynchronously to the clipboard. You will learn how to check for the availability of the API and use it to write text to the clipboard. By the end of this lab, you will have a solid understanding of how to use the Clipboard API in your JavaScript applications.
Function to Copy a String to the Clipboard
To copy a string to the clipboard, use the copyToClipboardAsync function. The function returns a promise that resolves when the clipboard's contents have been updated. Here are the steps:
- Check if the Clipboard API is available by verifying if
Navigator,Navigator.clipboard, andNavigator.clipboard.writeTextare truthy using anifstatement. - If the Clipboard API is available, use
Clipboard.writeText()to write the given value,str, to the clipboard. - Return the result of
Clipboard.writeText(), which is a promise that resolves when the clipboard's contents have been updated. - If the Clipboard API is not available, reject the promise with an appropriate error message using
Promise.reject(). - If you need to support older browsers, use
Document.execCommand()instead ofClipboard.writeText(). You can find out more about it in thecopyToClipboardsnippet.
Here's the copyToClipboardAsync function:
const copyToClipboardAsync = (str) => {
if (navigator && navigator.clipboard && navigator.clipboard.writeText) {
return navigator.clipboard.writeText(str);
}
return Promise.reject("The Clipboard API is not available.");
};
To use the function, call copyToClipboardAsync with the string you want to copy as an argument, like this:
copyToClipboardAsync("Lorem ipsum"); // 'Lorem ipsum' copied to clipboard.
Summary
Congratulations! You have completed the Copy to Clipboard Async lab. You can practice more labs in LabEx to improve your skills.