可以将剪贴板 text/html mimetype 复制到 javascript 中的 text/plain 吗?

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

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

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

最好直接在copy的时候处理。由于 text/html 应该只在从选择而不是从输入复制时设置,我们可以通过范围 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" 事件。

但是,除了 plain/text 从剪贴板 API,似乎没有浏览器真正支持读取任何其他内容,这只剩下粘贴事件:

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>