繁体   English   中英

可以将剪贴板文本/html mimetype 复制到 javascript 中的文本/纯文本吗?

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

假设我有从复制到剪贴板事件(例如document.execCommand )生成的text/html

有没有办法将该数据复制到text/plain mimetype 中而不会丢失text/html数据? 如果是这样,如何做到这一点? 请注意,我当前在复制剪贴板中有 text/html 数据,不能同时写入两者。

最好的可能是直接在复制时处理它。 由于text/html应该只在从 Selection 复制而不是从输入复制时设置,我们可以通过 Range API 获取标记,并覆盖我们复制事件的数据。

 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>

现在OP说他们当时不能这样做,因为我不知道是什么原因。
这意味着他们需要能够读取剪贴板的内容,为此,他们需要用户的批准,或者通过剪贴板 API 的权限,或者通过处理"paste"事件。

但是,似乎没有浏览器真正支持从剪贴板 API 中读取plain/text以外的任何内容,这让我们只剩下粘贴事件:

 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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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