Reappearance:
here:
)
window.onload = function() { const info = document.querySelector('.info'), pinfo = document.querySelector('.paste-info'), target = document.querySelector('.target'); setInterval(() => { const sel = ".source *, .target *" info.innerHTML = ''; for (const elm of [...document.querySelectorAll(sel)]) { info.innerHTML += "TAG: " + elm.tagName + "; TEXT: " + elm.innerText + "; FONTSIZE: " + window.getComputedStyle(elm)['font-size'] + "<br>"; } }, 1000); target.addEventListener('paste', function(e) { pinfo.innerHTML += "PASTE HTML: <pre>" + e.clipboardData.getData('text/html').replaceAll('<', '<').replaceAll('>', '>') + '</pre><br>'; }); };
div[contenteditable] { border: 1px solid black; }
<div class="source" contenteditable=true>Source text: <b>foobar</b></div> <div style="font-size: 14px"> <div contenteditable=true class="target">Destination, <h1>paste here:</h1></div> </div> <div class="info"></div> <div class="paste-info"></div>
You will notice:
<b>foobar</b>
(see what follows PASTE HTML:
), but...style="font-size: 14px;"
set on the b
element (the 14px size comes from the contenteditable's parent). I want no font sizes set on the pasted HTML because they are not specified in the source clipboard data.
Question: How do I force Chrome not to put any font size on the pasted HTML when there is no font size on the source HTML?
I tried a workaround: setting font-size: unset/revert
on the source, but this resulted in font-size: unset
also appearing in the pasted HTML middle. I don't want any font size to appear in the pasted HTML.
The context of this code is a Chrome extension where I control the text/html data pasted into the target. I can attach a paste event listener on the target contenteditable, but I cannot change the HTML/style of the content after it is pasted.
Maybe intercept the paste event and change the pasted content to force it to be pasted as plain text using js.
I added the id of
id="editor"
on thecontenteditable
div. And add the following js code:This is a snippet of it running. Let me know if this solves your problem:
You can use to select API.
The steps are
Range
object representing the current selection.Range
object to parse the pasted HTML markup into aDocumentFragment
object, thanks to thecreateContextualFragment()
method.Range#deleteContents()
).DocumentFragment
object we created at step 2, where the cursor is.Range
object so that the cursor moves to the end of the newly pasted content.Performing all of these steps manually will prevent the browser from "intelligently" processing rich text content; only parsing the content in the clipboard.