Introduction to Clipboard API
The Clipboard API provides a way to interact with the clipboard, allowing you to programmatically copy, cut, and paste text and other content. This is incredibly useful for web applications that aim to enhance user experiences by handling clipboard operations seamlessly.
Understanding Clipboard API Methods
Below are some of the key methods and properties of the Clipboard API, along with examples to help you get started.
Write to Clipboard
Use the navigator.clipboard.writeText()
method to write text to the clipboard.
navigator.clipboard.writeText('Hello Clipboard!').then(function() {
console.log('Text copied to clipboard');
}).catch(function(error) {
console.error('Error writing text to clipboard: ', error);
});
Read from Clipboard
Use the navigator.clipboard.readText()
method to read text from the clipboard.
navigator.clipboard.readText().then(function(text) {
console.log('Text read from clipboard: ', text);
}).catch(function(error) {
console.error('Error reading text from clipboard: ', error);
});
Writing Images to Clipboard
You can also write images to the clipboard with navigator.clipboard.write()
.
const imageBlob = new Blob(['image data here'], { type: 'image/png' });
const clipboardItem = new ClipboardItem({ 'image/png': imageBlob });
navigator.clipboard.write([clipboardItem]).then(function() {
console.log('Image copied to clipboard');
}).catch(function(error) {
console.error('Error writing image to clipboard: ', error);
});
App Example Using Clipboard API
Let’s build a simple web application that uses these APIs.
HTML Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Clipboard API Example</title>
</head>
<body>
<h1>Clipboard API Demo</h1>
<textarea id="textarea" placeholder="Type something here..."></textarea>
<button onclick="copyText()">Copy Text</button>
<button onclick="pasteText()">Paste Text</button>
<script>
function copyText() {
const text = document.getElementById('textarea').value;
navigator.clipboard.writeText(text).then(function() {
alert('Text copied to clipboard');
}).catch(function(error) {
console.error('Error copying text: ', error);
});
}
function pasteText() {
navigator.clipboard.readText().then(function(text) {
document.getElementById('textarea').value = text;
}).catch(function(error) {
console.error('Error pasting text: ', error);
});
}
</script>
</body>
</html>
This simple example demonstrates how to copy and paste text using the Clipboard API. Use this as a foundation to build more complex clipboard functionalities in your applications.
Hash: a78c94675455b6203686c7f220c225c90d386a52a623c547bfce8bbbac94c31c