Paste Clipboard to Input Field using JavaScript
JavaScript paste clipboard to input field. Want to allow users to paste clipboard content into an input field with a single click? This tutorial shows you how to use modern JavaScript to access clipboard data and automatically insert it into an input box. Works in most modern browsers.
Contents
Demo: Paste Clipboard Content
Click the button below to paste text from your clipboard into the input field. This demo uses the Clipboard API with permission and error handling.
<input type="text" id="pasteInput" placeholder="Paste appears here" />
<button id="pasteButton">Paste</button>
const pasteInput = document.getElementById('pasteInput');
const pasteButton = document.getElementById('pasteButton');
async function pasteClipboardToInput() {
try {
// Check if the Clipboard API is supported by the browser
if (!navigator.clipboard || !navigator.clipboard.readText) {
alert('Your browser does not support the Clipboard API.');
return;
}
// Request permission to read from the clipboard
// The Permissions API allows checking and requesting permissions
const permissionStatus = await navigator.permissions.query({ name: 'clipboard-read' });
if (permissionStatus.state === 'granted' || permissionStatus.state === 'prompt') {
// Permission is granted or user will be prompted
const clipboardText = await navigator.clipboard.readText();
if (clipboardText) {
pasteInput.value = clipboardText;
// Trigger input event to notify any listeners
// inputElement.dispatchEvent(new Event('input', { bubbles: true }));
// alert('Clipboard content successfully pasted!');
} else {
alert('No text found on the clipboard.');
}
} else if (permissionStatus.state === 'denied') {
// Permission was denied by the user
alert('Permission to read clipboard denied. Please grant permission in your browser settings.');
}
} catch (error) {
// Catch any errors during the clipboard read operation
if (error.name === 'NotAllowedError') {
alert('Permission to read clipboard was denied or not granted. Please click the button again and allow access if prompted.');
} else if (error.name === 'SecurityError') {
alert('Clipboard access is restricted in this context (e.g., not served over HTTPS or in an iframe without proper permissions).');
} else {
alert(`An unexpected error occurred: ${error.message}`);
}
}
}
// usage
// Add event listener to the paste button
pasteButton.addEventListener('click', pasteClipboardToInput);
Multiple inputs paste clipboard. You can use a single JavaScript function to paste clipboard text into multiple input fields. Each paste button can target its corresponding input by passing the input element to the reusable function.This approach avoids code duplication and keeps your JavaScript clean and modular.
Demo:
<div>
<label>Input 1:</label>
<input type="text" id="input1" placeholder="Paste here 1">
<button onclick="pasteClipboardToInput(document.getElementById('input1'))">Paste</button>
</div>
<br>
<div>
<label>Input 2:</label>
<input type="text" id="input2" placeholder="Paste here 2">
<button onclick="pasteClipboardToInput(document.getElementById('input2'))">Paste</button>
</div>
async function pasteClipboardToInput(inputElement) {
try {
if (!navigator.clipboard || !navigator.clipboard.readText) {
alert('Your browser does not support the Clipboard API.');
return;
}
const permissionStatus = await navigator.permissions.query({ name: 'clipboard-read' });
if (permissionStatus.state === 'granted' || permissionStatus.state === 'prompt') {
const clipboardText = await navigator.clipboard.readText();
if (clipboardText) {
inputElement.value = clipboardText;
// Trigger input event to notify any listeners
// inputElement.dispatchEvent(new Event('input', { bubbles: true }));
} else {
alert('Clipboard is empty.');
}
} else {
alert('Permission to access clipboard was denied.');
}
} catch (error) {
alert(`Error: ${error.message}`);
}
}
This method allows each paste button to target the input field directly next to it its sibling without needing to assign unique ID. Using this.previousElementSibling
, the button accesses the related input and pastes the clipboard content. It simplifies your HTML when working with multiple input button pairs.
Demo Sibling Input Field:
<div>
<input type="text" placeholder="Paste here 1">
<button onclick="pasteToSiblingInput(this)">Paste</button>
</div>
<br>
<div>
<input type="text" placeholder="Paste here 2">
<button onclick="pasteToSiblingInput(this)">Paste</button>
</div>
async function pasteToSiblingInput(button) {
const input = button.previousElementSibling;
try {
if (!navigator.clipboard || !navigator.clipboard.readText) {
alert('Clipboard API is not supported in this browser.');
return;
}
const permission = await navigator.permissions.query({ name: 'clipboard-read' });
if (permission.state === 'granted' || permission.state === 'prompt') {
const text = await navigator.clipboard.readText();
input.value = text || '';
// Trigger input event to notify any listeners
// inputElement.dispatchEvent(new Event('input', { bubbles: true }));
} else {
alert('Clipboard permission denied.');
}
} catch (err) {
alert(`Clipboard read failed: ${err.message}`);
}
}
If the Clipboard API is not working as expected, it could be due to browser restrictions, permission settings, or security policies. Here are the most common reasons and how to resolve them:
- Not Served Over HTTPS: Clipboard API only works on secure origins (HTTPS). Make sure your website uses HTTPS, not HTTP.
- Old or Unsupported Browser: Some older browsers or versions do not support
navigator.clipboard.readText()
. Use the latest version of Chrome, Edge, Firefox, or Safari. - No Clipboard Permission: Users may have denied clipboard permissions. Browsers may also block clipboard access unless it is triggered by a user interaction like a button click.
- Running Inside an Iframe: Clipboard access may be restricted inside iframes unless the proper
allow="clipboard-read; clipboard-write"
attribute is set. - Using localhost with Insecure Context: While
localhost
is considered a secure context during development, it may still behave differently from live HTTPS hosting. - Clipboard Is Empty: If there is nothing copied in the clipboard, the paste will return an empty string. Always check
clipboardText
before inserting.
Related: