简体   繁体   中英

Possible to copy Clipboard text/html mimetype to text/plain in javascript?

Let's say I have text/html that has been generated from a copy-to-clipboard event (such as document.execCommand ).

Is there a way to copy that data into the text/plain mimetype without losing the text/html data? If so, how could this be done? Note that I have text/html data currently in the copy clipboard and it's not an option to write both at the same time.

The best is probably to handle it at the copying directly. Since text/html should be set only when copying from the Selection and not from inputs, we can get the markup through the Range API, and overwrite the data of our copy event.

 addEventListener( "copy", (evt) => { const selection = getSelection(); if( selection.isCollapsed ) return; evt.preventDefault(); const range = selection.getRangeAt(0); const data_as_html = new XMLSerializer().serializeToString( range.cloneContents() ); evt.clipboardData.setData("text/plain", data_as_html); evt.clipboardData.setData("text/html", data_as_html); } );
 <p> <span style="color:red;font-weight:bold">copy</span><span style="color:green;font-weight:thinner"> this</span> <span style="color:blue"> text</span> </p> <div contenteditable>Paste here as rich-text</div> <textarea cols="30" rows="10">Paste here as markup</textarea>

Now OP said they can't do it at that time, for I don't know what reasons.
This means they need to be able to read the content of the clipboard, and for this, they need the user's approval, either through the Clipboard API's Permissions, or by handling a "paste" event.

However, it seems no browser really supports reading anything else than plain/text from the Clipboard API, which leaves us only the paste event:

 btn.onclick = (evt) => { addEventListener( "paste", (evt) => { const data_as_html = evt.clipboardData.getData("text/html"); if( data_as_html ) { } addEventListener("copy", (evt) => { evt.preventDefault(); evt.clipboardData.setData("text/plain", data_as_html); evt.clipboardData.setData("text/html", data_as_html); }, { once: true } ); document.execCommand("copy"); }, { once: true } ); document.execCommand("paste"); }
 <button id="btn">convert clipboard content to markup</button><br> <p> <span style="color:red;font-weight:bold">copy</span><span style="color:green;font-weight:thinner"> this</span> <span style="color:blue"> text</span> </p> <div contenteditable>Paste here as rich-text</div> <textarea cols="30" rows="10">Paste here as markup</textarea>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM