Module 43 : Clipboard API
1. What is the Clipboard API?
The Clipboard API is a modern asynchronous API available in JavaScript used for:
Reading text from the clipboard: readText()
Writing text to the clipboard: writeText()
Note: Clipboard access is only available in secure contexts (HTTPS) and often requires user gestures like a button click.
2. Security Considerations
The API works only on HTTPS or localhost.
Clipboard read operations may be blocked unless triggered by user interaction.
Access may prompt for permission.
if (!navigator.clipboard) { console.log("Clipboard API not supported!"); }
3. Clipboard API Methods
🔸 navigator.clipboard.writeText(text)
Copies a given string to the clipboard.
✅ Example:
<button id="copyBtn">Copy Text</button> <input type="text" id="copyInput" value="Hello Clipboard API!"> <script> document.getElementById("copyBtn").onclick = function() { const inputText = document.getElementById("copyInput").value; navigator.clipboard.writeText(inputText) .then(() => alert("Text copied to clipboard!")) .catch(err => console.error("Copy failed:", err)); }; </script>
🔸 navigator.clipboard.readText()
Reads text content from the clipboard.
✅ Example:
<button id="pasteBtn">Paste Text</button> <input type="text" id="pasteInput" placeholder="Paste here"> <script> document.getElementById("pasteBtn").onclick = function() { navigator.clipboard.readText() .then(text => { document.getElementById("pasteInput").value = text; }) .catch(err => console.error("Paste failed:", err)); }; </script>
4. Building a Clipboard Tool
Objective:
Build a mini tool with the following features:
Copy input text
Paste into another field
HTML + JS Code:
<h3>Clipboard Lab</h3> <textarea id="textInput" rows="3" placeholder="Type something..."></textarea><br> <button onclick="copyText()">Copy</button> <button onclick="pasteText()">Paste</button> <textarea id="outputArea" rows="3" placeholder="Pasted content..."></textarea> <script> function copyText() { const text = document.getElementById("textInput").value; navigator.clipboard.writeText(text) .then(() => alert("Copied!")) .catch(err => console.error("Copy error:", err)); } function pasteText() { navigator.clipboard.readText() .then(text => { document.getElementById("outputArea").value = text; }) .catch(err => console.error("Paste error:", err)); } </script>
🔍 Explanation:
User writes in the first box.
On clicking "Copy", text is stored in clipboard.
On clicking "Paste", it’s fetched and inserted into the second box.
🧠 5. Exercises
📝 Exercise 1: Copy Email Address
Create a button that copies an email address to the clipboard.
<p>Email: <span id="email">example@mail.com</span></p> <button onclick="copyEmail()">Copy Email</button> <script> function copyEmail() { const email = document.getElementById("email").innerText; navigator.clipboard.writeText(email) .then(() => alert("Email copied!")) .catch(err => console.error(err)); } </script>
Exercise 2: Detect Clipboard Support
Add a check to inform users if their browser doesn’t support clipboard.
if (!navigator.clipboard) { alert("Your browser doesn't support Clipboard API!"); }
6. Research. Use Cases
✅ Common Applications:
Use Case
Example
Social sharing
"Copy link to post"
Form autofill
Paste from clipboard into forms
Code copying
“Copy code” buttons on documentation pages
Online tools
Text manipulation and editors (like Notion or Grammarly)
Research:
Browsers like Chrome and Edge allow clipboard access only with user gestures.
On Firefox, readText() prompts for permission every time.
Clipboard API may be limited in Safari or mobile browsers.
Use Permissions API to check access (experimental):
navigator.permissions.query({ name: "clipboard-read" }).then(result => { console.log(result.state); // granted | denied | prompt });
🔧 7. Debugging Tips
Problem
Cause
Solution
navigator.clipboard is undefined
Insecure HTTP page
Use HTTPS or localhost
Permission denied
No user interaction
Use click event
Clipboard not working on mobile
Partial support
Check browser compatibility
✅ Summary
Clipboard API is asynchronous, secure, and powerful.
Use writeText() to copy and readText() to paste.
Always handle permission errors gracefully.
Build practical tools (copy buttons, paste forms, etc.) using the API.
Review Questions
What are the two main methods of the Clipboard API?
Why must clipboard operations be in response to user actions?
Write a code snippet that copies a paragraph’s text to clipboard.
How do you detect if Clipboard API is supported?
Describe one use case for readText().
No comments:
Post a Comment