JavaScript provides a method called document.execCommand('copy')
which can be used to copy text to the clipboard. However, this method is now considered obsolete and should not be used. The modern and recommended way of copying to the clipboard is by using the Clipboard API, which is a part of the Web API.
Here is an example of how to copy text to the clipboard using the Clipboard API:
// Get the text you want to copy
const textToCopy = "Hello World!";
// Create a textarea element
const textarea = document.createElement("textarea");
// Set the text and style the textarea
textarea.value = textToCopy;
textarea.style.position = "fixed"; // Prevent scrolling to bottom of page in MS Edge
document.body.appendChild(textarea);
// Select the text
textarea.select();
// Copy the text
document.execCommand("copy");
// Remove the textarea
document.body.removeChild(textarea);
console.log("Text copied to clipboard: " + textToCopy);
You can also use the Clipboard API writeText()
method for copying the text to clipboard
navigator.clipboard.writeText("Hello World!").then(() => {
console.log("Text copied to clipboard");
}, (err) => {
console.log("Could not copy text: ", err);
});
It is also possible to copy other types of data to the clipboard, such as images and files. The Clipboard API provides methods for doing this as well.
// Copy an image to clipboard
const img = document.getElementById("myImg");
navigator.clipboard.write([new ClipboardItem({'image/png': img})]);
// Copy a file to clipboard
const file = new File(["Hello World!"], "hello.txt", {type: "text/plain"});
navigator.clipboard.write([new ClipboardItem({'text/plain': file})]);
Note that the Clipboard API is currently only supported by a limited number of browsers, including Google Chrome, Firefox and Edge (Chromium based). You can check browser support for the Clipboard API by visiting the following link: https://caniuse.com/#search=clipboard