H5 copy paste - execCommand

Window.clipboarddata (only available in IE)

It's a good object to use, but only in IE,
It took IE ten thousand years to find out that he had a good place
IE is about to quit history. Find something else

Compatibility (can I use)

brief introduction
When the document object is converted to design mode (select, set contentEditable, etc.), the document object provides an execCommand method, which can operate the content of the editable region by passing parameter commands to this method. Most of the commands of this method are operations on the selected area of the document
(such as bold, italics, etc.), you can also insert an element (such as adding an a link) or modify a complete line (such as indenting). When the element is set to contentEditable, execute execCommand
Method can perform many operations on the current active element.

Today we only use copy

The introduction says that when the document object is converted to design mode (select, set content editable, etc.), the document object provides an execCommand method

But we don't want to have a textarea at all. Otherwise, what's the difference with window.prompt?

The simplest and most effective way is to hide the textarea

const copy = text => {
  const textarea = document.createElement("textarea")
  textarea.style.position = 'fixed'
  textarea.style.top = 0
  textarea.style.left = 0
  textarea.style.border = 'none'
  textarea.style.outline = 'none'
  textarea.style.resize = 'none'
  textarea.style.background = 'transparent'
  textarea.style.color = 'transparent'

  textArea.value = text
  try {
    const msg = document.execCommand('copy') ? 'successful' : 'unsuccessful'
  } catch (err) {
    console.log('unable to copy', err)


<!DOCTYPE html>
<html lang="en">
  <meta charset="UTF-8">
  <title>copy example</title>

<h5>To me, my lovely fat man</h5>
  <button class="copy">Copy</button>
  <textarea cols="50" rows="10" placeholder="Let's paste it here!"></textarea>


  var copyBtn = document.querySelector('.copy')

  // Just call copyTextToClipboard() when you click
  copyBtn.onclick = function() {
    copyTextToClipboard('Try to copy something')

  function copyTextToClipboard(text) {
    var textArea = document.createElement("textarea")

    textArea.style.position = 'fixed'
    textArea.style.top = 0
    textArea.style.left = 0
    textArea.style.width = '2em'
    textArea.style.height = '2em'
    textArea.style.padding = 0
    textArea.style.border = 'none'
    textArea.style.outline = 'none'
    textArea.style.boxShadow = 'none'
    textArea.style.background = 'transparent'
    textArea.value = text



    try {
      var msg = document.execCommand('copy') ? 'Success' : 'fail'
      console.log('Copy content ' + msg)
    } catch (err) {
      console.log('You cannot copy content in this way')




Keywords: Front-end IE

Added by advoor on Sun, 17 Nov 2019 21:09:17 +0200