set clipboard in javascript

To set the content of the clipboard in JavaScript, you can use the Clipboard API, specifically the writeText() method. This method takes a string parameter for the content to be copied to the clipboard.

Here's an example code snippet that shows how to copy text to the clipboard:

index.tsx
// Get the text to copy
const textToCopy = "Hello, world!";

// Use the Clipboard API to copy the text
navigator.clipboard.writeText(textToCopy)
  .then(() => {
    console.log("Text copied to clipboard");
  })
  .catch((error) => {
    console.error("Error copying text to clipboard:", error);
  });
301 chars
12 lines

In this code, we first define the text that we want to copy to the clipboard using a string variable textToCopy. We then use the navigator.clipboard.writeText() method to copy the text to the clipboard. This method returns a promise, so we can use .then() to handle the success case and .catch() to handle the error case.

Note that the navigator.clipboard API only works in secure contexts (i.e. HTTPS) on most browsers.

gistlibby LogSnag