JSFiddle - React, Tailwind, and code Playground

by tomprogramming

HTML

<script src="http://tomprogramming.com/Files/rangy-core.js"></script>
<h3>Copy from here</h3>
<div contenteditable="true" id="copiable">

</div>
<h3>Paste into here</h3>
<div contenteditable="true" id="pastable">

</div>
<div id="status">
</div>

CSS

[contenteditable=true] {
margin:20px;
 padding:10px;
border:1px dashed red;   
}

JavaScript

var statusDiv = $("#status");
$("#copiable").on("copy", function(e){
    statusDiv.append("<p>You copied text</p>");
    console.log(e);

    var clipboard = '<div data-copiedfrom="libraryaware">' + rangy.getSelection().toHtml() + "</div>";
    e.originalEvent.clipboardData.setData('text/html', clipboard);
    
    e.preventDefault();
    e.stopPropagation();
});


$("#pastable").on("paste", function(e){
    
    console.log(e);
    var doc = e.originalEvent.clipboardData.getData('text/html');
    var copiedText = $(doc).filter('[data-copiedfrom="libraryaware"]');

    if (copiedText.length > 0){
        statusDiv.append("<p>You pasted text from a good source</p>");    
        rangy.getSelection().getRangeAt(0).insertNode(copiedText);
        copiedText.contents().unwrap();//remove the scaffolding
    }else{
        statusDiv.append("<p>You pasted text from an invalid source</p>");   
    }
    e.preventDefault();
    e.stopPropagation();
});