paste as plain text (async clipboard api)

by Jason Miller

HTML

<div contentEditable id="input">
  <h2>Edit Me!</h2>
  <p>Hello, world.</p>
</div>

<hr>
<h4>Output:</h4>
<pre id="output"></pre>

CSS

html, body {
  background: #f9f9f9;
}

[contentEditable] {
  margin: 10px;
  padding: 10px;
  border: 1px solid #ccc;
  background: #fff;
}

JavaScript

// Example:
//   Implementing "Paste as Plain Text" in Chrome 66+
document.addEventListener('paste', async e => {
  e.preventDefault();
  let text;
  if (await navigator.permissions.query({ name: 'clipboard-read' }).state==='granted') {
    try {
      text = await navigator.clipboard.readText();
    } catch (err) {}
  }

	// we got denied, but there's always the old way:
  console.log(text);
  if (text==null) {
    text = e.clipboardData.getData('text/plain');
  }
  
  // insert plaintext at cursor (replacing any selection)
  let sel = document.getSelection();
  let range;
  for (let i=sel.rangeCount; i--; ) {
  	range = sel.getRangeAt(i);
    range.deleteContents();
    if (i!==0) sel.removeRange(range);
  }
  if (!range) sel.addRange(range = document.createRange());
  range.insertNode(document.createTextNode(text));
  
  // fire an input event
  e.target.dispatchEvent(new Event('input',{bubbles:true}));
});


(input.oninput = () => {
	output.textContent = input.innerHTML;
})();