Clipboard api (clipboard)
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', async () => {
try {
await copyInClipboard(editorElement.innerHTML);
alert('Copy status: true');
} catch(e) {
alert('Copy status: false');
console.error(e);
}
});
async function copyInClipboard(content) {
const itemHtml = createClipboardItem(content, 'text/html');
const itemText = createClipboardItem(removeTags(content), 'text/html');
// await navigator.clipboard.write([itemHtml, itemText]); // not allowed: https://bugs.chromium.org/p/chromium/issues/detail?id=1171260
await navigator.clipboard.write([itemHtml]);
//await navigator.clipboard.writeText(contentText);
}
function createClipboardItem(content, type) {
const blobInput = new Blob([content], { type });
const clipboardItemInput = new ClipboardItem({ [blobInput.type]: blobInput });
return clipboardItemInput
}
function removeTags(str) {
if (!str) {
return str;
}
return str.replace( /(<([^>]+)>)/ig, '');
}