<div class="container">
  <h2>Accessing the Clipboard using execCommand()</h2>
  
  <h3>Copy</h3>
  <p id="content-copy">This text will be inserted into the clipboard.</p>
  <button id="button-copy">Copy Text</button>
  
  <h3>Cut</h3>
  <input id="content-cut" type="text" value="This text will be cut, then inserted into the clipboard." />
  <button id="button-cut">Cut Text</button>
  
  <h3>Paste</h3>
  <textarea placeholder="Press Ctrl + V to paste the clipboard's current content." rows="10"></textarea>
</div>
document.addEventListener("DOMContentLoaded", () => {
  const $ = document.querySelector.bind(document);
  const contentCopyElm = $("#content-copy"),
        inputCutElm = $("#content-cut"),
        buttonCopyElm = $("#button-copy"),
        buttonCutElm = $("#button-cut");
  
  const isSupported = (cmd) => {
    return document.queryCommandSupported(cmd);
  }
  
  buttonCopyElm.addEventListener("click", () => {
    // We will need a range object and a selection.
    const range = document.createRange(),
          selection = window.getSelection();

    // Clear selection from any previous data.
    selection.removeAllRanges();

    // Make the range select the entire content of the element.
    range.selectNodeContents(contentCopyElm);

    // Add that range to the selection.
    selection.addRange(range);

    // Try to copy the selection to the clipboard.
    try {
      if(isSupported("copy")) document.execCommand("copy");
      else alert(`execCommand("copy") is not supported in your browser.`);
    } catch(e) {
      console.log(e);
    }
    
    // Clear selection if you want to.
    selection.removeAllRanges();
  });
  
  buttonCutElm.addEventListener("click", () => {
    // Select the content of the input
    inputCutElm.select();
    
    // Try to cut the content of the input
    try {
      if (isSupported("cut")) document.execCommand("cut");
      else alert(`execCommand("cut") is not supported in your browser.`);
    } catch(e) {
      console.log(e);
    }
  });
});

/**
* https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Interact_with_the_clipboard
* https://alligator.io/js/copying-to-clipboard/
* https://codepen.io/chrisdavidmills/full/gzYjag/
* https://tutorialzine.com/2016/10/quick-tip-accessing-the-clipboard-with-javascript
*/
Run Pen

External CSS

  1. https://codepen.io/completejavascript/pen/RqpPye.css

External JavaScript

This Pen doesn't use any external JavaScript resources.