Javascript - Copy string to clipboard as text/html

前端 未结 3 1983
慢半拍i
慢半拍i 2020-12-03 02:49

Is there a way in javascript to copy an html string (ie xx) into the clipboard as text/html, so that it can then be pasted into for example a

3条回答
  •  借酒劲吻你
    2020-12-03 03:08

    I have done a few modifications on Loilo's answer above:

    • setting (and later restoring) the focus to the hidden div prevents FF going into endless recursion when copying from a textarea

    • setting the range to the inner children of the div prevents chrome inserting an extra
      in the beginning

    • removeAllRanges on getSelection() prevents appending to existing selection (possibly not needed)

    • try/catch around execCommand

    • hiding the copy div better

    On OSX this will not work. Safari does not support execCommand and chrome OSX has a known bug https://bugs.chromium.org/p/chromium/issues/detail?id=552975

    code:

    clipboardDiv = document.createElement('div');
    clipboardDiv.style.fontSize = '12pt'; // Prevent zooming on iOS
    // Reset box model
    clipboardDiv.style.border = '0';
    clipboardDiv.style.padding = '0';
    clipboardDiv.style.margin = '0';
    // Move element out of screen 
    clipboardDiv.style.position = 'fixed';
    clipboardDiv.style['right'] = '-9999px';
    clipboardDiv.style.top = (window.pageYOffset || document.documentElement.scrollTop) + 'px';
    // more hiding
    clipboardDiv.setAttribute('readonly', '');
    clipboardDiv.style.opacity = 0;
    clipboardDiv.style.pointerEvents = 'none';
    clipboardDiv.style.zIndex = -1;
    clipboardDiv.setAttribute('tabindex', '0'); // so it can be focused
    clipboardDiv.innerHTML = '';
    document.body.appendChild(clipboardDiv);
    
    function copyHtmlToClipboard(html) {
      clipboardDiv.innerHTML=html;
    
      var focused=document.activeElement;
      clipboardDiv.focus();
    
      window.getSelection().removeAllRanges();  
      var range = document.createRange(); 
      range.setStartBefore(clipboardDiv.firstChild);
      range.setEndAfter(clipboardDiv.lastChild);
      window.getSelection().addRange(range);  
    
      var ok=false;
      try {
         if (document.execCommand('copy')) ok=true; else utils.log('execCommand returned false !');
      } catch (err) {
         utils.log('execCommand failed ! exception '+err);
      }
    
      focused.focus();
    }
    

    see jsfiddle where you can enter html segment into the textarea and copy to the clipboard with ctrl+c.

提交回复
热议问题