DEV Community

Mohamed Idris
Mohamed Idris

Posted on

How to Copy to Clipboard in JS

To copy text to the clipboard in JavaScript, we first need to check if we have access to the clipboard. If we do, we can try to copy the text. If it fails, we can catch the error and show a message. Here's an example:

const saveToClipboard = async (text) => {
  if (navigator.clipboard) {
    try {
      // Try to copy the text to the clipboard
      await navigator.clipboard.writeText(text);
      toast.success("Text copied to clipboard!");
    } catch (error) {
      // Show an error message if copying fails
      toast.error("Failed to copy text to clipboard!");
    }
  } else {
    // Show an error if clipboard access is not available
    toast.error("Clipboard access is not available!");
  }
};
Enter fullscreen mode Exit fullscreen mode

This function will check if clipboard access is available, attempt to copy the text to the clipboard, and handle any errors that occur. If successful, a success message will appear; if not, it will show an error message.

Top comments (0)