Frontend Development 11 min read

Implementing One‑Click Copy in JavaScript: Clipboard API and Fallback Methods

This article explains how to implement a one‑click copy feature in web pages using the modern Clipboard API for text and images, provides compatibility notes, and offers fallback code with document.execCommand('copy') for older browsers and WebViews.

TAL Education Technology
TAL Education Technology
TAL Education Technology
Implementing One‑Click Copy in JavaScript: Clipboard API and Fallback Methods

In many IM chat windows, web code editors, or forum posts, a “one‑click copy” feature is often needed to let users quickly copy text or images.

The article first reviews the modern Clipboard API (navigator.clipboard.writeText and navigator.clipboard.write) and its compatibility, noting that newer browsers support it but some Android Firefox versions and WebViews may not.

It provides code examples for writing text:

navigator.clipboard.writeText("text to copy")
  .then(() => { /* success */ }, () => { /* failure */ });

and for writing images using ClipboardItem:

navigator.clipboard.write([new ClipboardItem({ [blob.type]: blob })])
  .then(() => { /* success */ }, (error) => { /* failure */ });

Because the Clipboard API may be unavailable, the article also covers the deprecated but still supported fallback document.execCommand('copy') , showing how to copy text by creating a temporary textarea and invoking the command, and how to copy images by selecting an img element via getSelection() and createRange() .

Code snippets for the fallback methods are included, along with notes on required user interaction and permission considerations.

Finally, the article summarizes the recommended modern approach and the necessary compatibility layer for older environments.

JavaScriptCompatibilityCopyClipboard API
TAL Education Technology
Written by

TAL Education Technology

TAL Education is a technology-driven education company committed to the mission of 'making education better through love and technology'. The TAL technology team has always been dedicated to educational technology research and innovation. This is the external platform of the TAL technology team, sharing weekly curated technical articles and recruitment information.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.