Clipboard api (execCommand direct mode)

by Julien Roche

HTML

<div role="textbox" hidefocus="true" contenteditable="true" spellcheck="false" style="border: 1px solid black; height: 20vh;" aria-multiline="true">
Some text to <b>copy/paste</b> into various container
</div>

<br />
<hr />
<br />
<button>Click me for copy</button>
<br />
<br />
<hr />
<br />

<section style="display: flex;">
  <fieldset style="flex: 1 1 auto;">
    <legend>Simple textarea (text/plain)</legend>
    <textarea style="resize: none; height: 10vh; width: 100%;"></textarea>
  </fieldset>
  
  <fieldset style="flex: 1 1 auto;">
    <legend>Rich editor (text/html)</legend>
    <div role="textbox" hidefocus="true" contenteditable="true" spellcheck="false" style="border: 1px solid black; height: 10vh;"></div>
  </fieldset>
</section>

JavaScript

const editorElement = document.querySelector('div[role="textbox"]');
const buttonElement = document.querySelector('button');
buttonElement.addEventListener('click', () => {
	const copyCommandSuccess = copyInClipboard(editorElement.innerHTML);
  alert('Copy status: ' + copyCommandSuccess);
});


function copyInClipboard(content) {
 
  document.addEventListener('copy', (event) => {
     event.preventDefault();
     event.clipboardData.setData('text/plain', removeTags(content));
     event.clipboardData.setData('text/html', content);
  }, { once: true });
  
  const copyCommandSuccess = document.execCommand('copy');
  
  return copyCommandSuccess;
}

function removeTags(str) {
    if (!str) {
        return str;
    }

    return str.replace( /(<([^>]+)>)/ig, '');
}