Open in a new tab

A Copy button for a code snippet and a Paste button that reads the clipboard; a missing API disables the button with a reason, and a refused permission is reported.

Uses @awacloud/fw (Apache-2.0). This example's code is Apache-2.0.

When to use it

A "copy" button next to a command, a token or a link, and a "paste" button that fills a field from the clipboard.

Copy-paste steps

  1. npm install @awacloud/fw
  2. Serve node_modules/@awacloud/fw/src/ at /vendor/fw/ (node serve.js from the examples root does this; any static server works).
  3. Copy index.html and main.js next to each other and open index.html on localhost or HTTPS: the asynchronous clipboard needs a secure context. The ../../_style/examples.css link is optional: copy that file along, or delete the link.

What it shows

  • clipboard.isSupported() returns { read, write, richWrite, share }: each button is enabled only when its half exists.
  • clipboard.set(text) and clipboard.get() return promises the browser may reject (no permission, the page not focused). The page catches the rejection, reports it, and gives the Copy button its label back, so it never shows a false "Copied" or leaves an unhandled rejection.
  • Not shown: setRich({ html, text }) for formatted content, and share(...) for the system share sheet.

Code

main.js

javascriptApache-2.038 lines

// SPDX-License-Identifier: Apache-2.0
import fw from '@awacloud/fw';
import { clipboard } from '@awacloud/fw/dom/utils/clipboard.js';

fw.runtime.registerAllDeep([clipboard]);
const CLIPBOARD = fw.runtime.resolve('clipboard');

/** @param {string} id */
const el = (id) => /** @type {HTMLElement} */ (document.getElementById(id));
const copyButton = /** @type {HTMLButtonElement} */ (el('copy'));
const pasteButton = /** @type {HTMLButtonElement} */ (el('paste'));
const status = el('status');

// Feature detection first: each button is disabled with a reason when its half is missing.
const { read, write } = CLIPBOARD.isSupported();
if (!write) copyButton.disabled = true;
if (!read) pasteButton.disabled = true;
if (!read || !write) status.textContent = 'No asynchronous clipboard here: it needs https or localhost.';

// Copy: the browser may refuse (no permission, the page not focused): say so, and give the label back.
copyButton.addEventListener('click', () => {
    CLIPBOARD.set(el('snippet').textContent ?? '')
        .then(() => {
            copyButton.textContent = 'Copied';
            setTimeout(() => { copyButton.textContent = 'Copy'; }, 2000);
        })
        .catch((/** @type {Error} */ err) => {
            copyButton.textContent = 'Copy';
            status.textContent = `Copy refused: ${err.message}`;
        });
});

// Paste: reading asks for a permission the user may deny.
pasteButton.addEventListener('click', () => {
    CLIPBOARD.get()
        .then((/** @type {string} */ text) => { el('pasted').textContent = text; })
        .catch((/** @type {Error} */ err) => { status.textContent = `Paste refused: ${err.message}`; });
});

index.html

htmlApache-2.025 lines

<!doctype html>
<!-- SPDX-License-Identifier: Apache-2.0 -->
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>fw · Copy and paste text</title>
  <link rel="stylesheet" href="../../_style/examples.css">
  <script type="importmap">
  { "imports": {
    "@awacloud/fw": "/vendor/fw/main.js", "@awacloud/fw/": "/vendor/fw/" } }
  </script>
  <script type="module" src="./main.js"></script>
</head>
<body>
  <main>
    <h1>Copy and paste text</h1>
    <pre><code id="snippet">npm install @awacloud/fw</code></pre>
    <button id="copy" type="button">Copy</button>
    <button id="paste" type="button">Paste</button>
    <p>Pasted: <output id="pasted">—</output></p>
    <p id="status" role="status"></p>
  </main>
</body>
</html>