Copy to clipboard with the Clipboard API
A “Copy” button next to a code block, a coupon code or a referral link is a few lines of JavaScript today. The asynchronous Clipboard API, navigator.clipboard.writeText(), works in all current browsers and returns a Promise, so there is no need for a library or for the old trick with a hidden textarea.
Problem: A theme needs “Copy” buttons for code blocks and for short values such as coupon codes, with feedback for the visitor and something sensible when copying is not allowed.
Solution: Call navigator.clipboard.writeText() from a click handler, show “Copied” for two seconds, and fall back to document.execCommand( 'copy' ) only where the Clipboard API is missing (plain HTTP, very old browsers).
The copy function
async function haCopy( text ) {
if ( navigator.clipboard && window.isSecureContext ) {
await navigator.clipboard.writeText( text );
return;
}
// Fallback: deprecated, but still the only option on plain HTTP
const ta = document.createElement( 'textarea' );
ta.value = text;
ta.setAttribute( 'readonly', '' );
ta.style.cssText = 'position:fixed;top:0;left:0;opacity:0';
document.body.appendChild( ta );
ta.select();
const ok = document.execCommand( 'copy' );
ta.remove();
if ( ! ok ) {
throw new Error( 'Copy failed' );
}
}
The Clipboard API is available only in a secure context (HTTPS or localhost) and only inside a user action such as a click. If the browser refuses, writeText() rejects, so the caller handles the error.
Buttons for values in the markup
<button type="button" class="ha-copy" data-copy="SPRING-15">Copy the coupon</button>
document.addEventListener( 'click', async ( event ) => {
const button = event.target.closest( '.ha-copy' );
if ( ! button ) {
return;
}
const label = button.textContent;
try {
await haCopy( button.dataset.copy );
button.textContent = 'Copied';
} catch ( error ) {
button.textContent = 'Press Ctrl+C to copy';
}
setTimeout( () => {
button.textContent = label;
}, 2000 );
} );
One listener on the document handles all buttons, also the ones added later by AJAX (see event delegation).
A button for every code block
document.querySelectorAll( 'pre > code' ).forEach( ( code ) => {
const pre = code.parentElement;
const button = document.createElement( 'button' );
button.type = 'button';
button.className = 'ha-copy-code';
button.textContent = 'Copy';
pre.style.position = 'relative';
pre.appendChild( button );
button.addEventListener( 'click', async () => {
try {
await haCopy( code.textContent );
button.textContent = 'Copied';
} catch ( error ) {
button.textContent = 'Failed';
}
setTimeout( () => {
button.textContent = 'Copy';
}, 2000 );
} );
} );
.ha-copy-code {
position: absolute;
top: 0.5rem;
right: 0.5rem;
padding: 0.25rem 0.6rem;
font-size: 0.75rem;
cursor: pointer;
}
Enqueue it
add_action( 'wp_enqueue_scripts', function () {
if ( is_singular() ) {
wp_enqueue_script( 'ha-copy', get_theme_file_uri( 'js/copy.js' ), [], '1.0.0', true );
}
} );
NOTE: Reading the clipboard (navigator.clipboard.readText()) is a different matter: the browser asks the visitor for permission, and Firefox did not support it on web pages at the time of writing. A copy button never needs it, so do not request it.