Copying text to the clipboard in JavaScript without user input can be achieved using the Clipboard API. This API allows developers to read and write data to the system clipboard. To copy text to the clipboard, the following steps can be taken:
Create a new ClipboardItem object with the text to be copied:
const text = "This text will be copied to the clipboard";
const item = new ClipboardItem({ "text/plain": new Blob([text], { type: "text/plain" }) });
Call the write() method of the navigator.clipboard object and pass in the ClipboardItem:
navigator.clipboard.write([item]).then(() => {
console.log("Text copied to clipboard");
}).catch((error) => {
console.error("Error copying text: ", error);
});
This will copy the text to the clipboard without requiring any user input.
JavaScript copy to clipboard without input example
Simple example code.
<!DOCTYPE html>
<html>
<head>
<title>Copy to Clipboard Example</title>
<script>
function copyToClipboard() {
const text = "This text will be copied to the clipboard";
navigator.clipboard.writeText(text).then(() => {
console.log("Text copied to clipboard");
}).catch((error) => {
console.error("Error copying text: ", error);
});
}
</script>
</head>
<body>
<button onclick="copyToClipboard()">Copy Text</button>
</body>
</html>
Output:
A function called copyToClipboard()
that uses the writeText
method of the Clipboard API to copy plain text to the clipboard. When the user clicks on the button on the HTML page, the function is called and the text is copied to the clipboard.
Do comment if you have any doubts or suggestions on this Js topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version