How can I copy to clipboard in HTML5 without using flash?

前端 未结 6 1309
一个人的身影
一个人的身影 2020-12-01 07:39

I want to use a copy-to-clipboard function in HTML5, but without using flash. Is it possible? How?

I tried to implement a copy-to-clipboad function with JavaScript,

6条回答
  •  眼角桃花
    2020-12-01 07:52

    UPDATE: This solution now works in the current version of all major browsers!

    function copyText(text){
      function selectElementText(element) {
        if (document.selection) {
          var range = document.body.createTextRange();
          range.moveToElementText(element);
          range.select();
        } else if (window.getSelection) {
          var range = document.createRange();
          range.selectNode(element);
          window.getSelection().removeAllRanges();
          window.getSelection().addRange(range);
        }
      }
      var element = document.createElement('DIV');
      element.textContent = text;
      document.body.appendChild(element);
      selectElementText(element);
      document.execCommand('copy');
      element.remove();
    }
    
    
    var txt = document.getElementById('txt');
    var btn = document.getElementById('btn');
    btn.addEventListener('click', function(){
      copyText(txt.value);
    })
    
    

    Note: Trying to use this solution to copy an empty string or a string that is only whitespace will not work.

    ALTERNATE, SIMPLIFIED SOLUTION

    This alternate solution has been tested in Chrome, Safari, and Firefox.

    const txt = document.querySelector('#txt')
    const btn = document.querySelector('#btn')
    
    const copy = (text) => {
      const textarea = document.createElement('textarea')
      document.body.appendChild(textarea)
      textarea.value = text
      textarea.select()
      document.execCommand('copy')
      textarea.remove()
    }
    
    btn.addEventListener('click', (e) => {
      copy(txt.value)
    })
    
    

    Note: This solution will not copy an empty string, but it will copy whitespace.

提交回复
热议问题