Copy Paste
by Dörnesz Tamás
HTML
<!--unformatted paste-->
<div id="html" style="color:red" contenteditable>Valami <em>rich</em> <span style="font-size:2em">HTML</span>
<table><tr><td>a</</td><td>b</</td></tr><tr><td>c</</td><td>d</</td></tr></table>
</div>
<div contenteditable id="edit">Unformatted</div>
<div contenteditable id="pastehtml2">Formatted</div>
<!--Click paste-->
<textarea onclick="paste(this)">Klikk</textarea>
<!--Copy this-->
<button onclick="copy()">copy txt</button>
<button onclick="paste3(document.getElementById('pastehtml2'))">paste3</button>
<button onclick="copypaste()">copy paste</button>
CSS
div[contenteditable], textarea {
border:1px solid red;
margin-bottom:4px;
display:block;
}
JavaScript
//unformatted paste
document.querySelector("div#edit").addEventListener("paste", function(e) {
e.preventDefault();
var text = e.clipboardData.getData("text/plain");
document.execCommand("insertHTML", false, text);
});
//Click paste
async function paste(element) {
const text = await navigator.clipboard.readText();
element.value = text;
}
//Copy this
function copy(){
copyToClipboard("I'm going to the clipboard !")
.then(() => console.log('text copied !'))
.catch(() => console.log('error'));
}
function copyToClipboard(textToCopy) {
if (navigator.clipboard && window.isSecureContext) {
return navigator.clipboard.writeText(textToCopy);
} else {
let textArea = document.createElement("textarea");
textArea.value = textToCopy;
textArea.style.position = "fixed";
textArea.style.left = "-999999px";
textArea.style.top = "-999999px";
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
return new Promise((res, rej) => {
document.execCommand('copy') ? res() : rej();
textArea.remove();
});
}
}
//Copy Paste
function copypaste(textToCopy) {
var from = document.getElementById('html');
var to = document.getElementById('pastehtml2');
copyElement(from);
paste3(to);
}
function copyElement(element) {
var body = document.body, range, sel;
if (document.createRange && window.getSelection) {
range = document.createRange();
sel = window.getSelection();
sel.removeAllRanges();
try {
range.selectNodeContents(element);
sel.addRange(range);
} catch (e) {
range.selectNode(el);
sel.addRange(range);
}
} else if (body.createTextRange) {
range = body.createTextRange();
range.moveToElementText(element);
range.select();
}
document.execCommand("Copy");
}
async function paste3(element) {
const items = await...