1. Use the API

  1. document.execCommand
  2. Async Clipboard API

2. Implementation

1. Function realization

  • inputCan be used to show what you want to copy.
  • Try to use the navigator. Clipboard. WriteText to write text to the operating system clipboard.
  • On failure, a call to document.getSelection() caches what the user has already selected (if any). 【Selection】
  • Select the text in the input, then use document.execcommand (“copy”), and the selected text will go to the clipboard.
  • Use selection.addrange () to restore the original Selection range. 【Range】
<div class="copy-input">
    <input id="copy-input" type="text" readonly value="http://www.baidu.com">
    <button onclick="copyInput()">copy</button>
</div>

<script>
    async function copyInput () {
      const inputDom = document.querySelector("#copy-input");

      try {
        return await navigator.clipboard.writeText(inputDom.value);
      } catch (error) {
        console.error(error);
      }

      const selected =
        document.getSelection().rangeCount > 0
          ? document.getSelection().getRangeAt(0)
          : false;

      inputDom.focus();
      inputDom.select();
      document.execCommand("copy");
      inputDom.setSelectionRange(0.0);
      inputDom.blur();

      if (selected) {
        document.getSelection().removeAllRanges();
        document.getSelection().addRange(selected); }}</script>
Copy the code

2. Implement a function to copy text to the clipboard.

On the basis of “copyToClipboard” added the navigator. The clipboard. WriteText calls.

  • Create a new<textarea>Element to which the content to copy is assigned, adding it to the HTML document.
  • The call document.getSelection() caches the content that the user has selected (if any).
  • usedocument.execCommand('copy')Copy to clipboard.
  • Delete from HTML document<textarea>Elements.
  • Use selection.addrange () to restore the original Selection range.
const copyToClipboard = async str => {
  try {
    return await navigator.clipboard.writeText(str);
  } catch (error) {
    console.error(error);
  }

  const el = document.createElement('textarea');
  el.value = str;
  el.setAttribute('readonly'.' ');
  el.style.position = 'absolute';
  el.style.left = '-9999px';
  document.body.appendChild(el);
  const selected =
    document.getSelection().rangeCount > 0
      ? document.getSelection().getRangeAt(0)
      : false;
  el.select();
  document.execCommand('copy');
  document.body.removeChild(el);
  if (selected) {
    document.getSelection().removeAllRanges();
    document.getSelection().addRange(selected); }};Copy the code

3. Expand – Copy images

// https://developer.mozilla.org/en-US/docs/Web/API/ClipboardItem/ClipboardItem
async function writeClipImg() {
  try {
    const imgURL = 'https://interactive-examples.mdn.mozilla.net/media/cc0-images/grapefruit-slice-332-332.jpg';
    const data = await fetch(imgURL);
    const blob = await data.blob();

    await navigator.clipboard.write([
      new ClipboardItem({
        [blob.type]: blob
      })
    ]);
    console.log('Fetched image copied.');
  } catch(err) {
    console.error(err.name, err.message); }}Copy the code

Reference documentation

  1. [execCommand issues and Thinking about alternatives]
  2. Clipboard API tutorial
  3. For 30 seconds – of – code “copyToClipboard”
  4. NPM Package 【Copy to clipboard】
  5. VS Code [BrowserClipboardService]