使用 navigator.clipboard 复制 HTML/富文本

Muh*_*kur 4 javascript clipboard copy copy-paste navigator

根据Clipboard Write API 规范,我可以复制到剪贴板,如下所示:

    const type = "text/plain";
    const text = "test plain";
    const blob = new Blob([text], { type });
    const data = [new ClipboardItem({ [type]: blob })];

    navigator.clipboard.write(data).then(
        () => {alert('success plain copy')},
        () => {}
    );
Run Code Online (Sandbox Code Playgroud)

我尝试过并且有效。但我尝试将类型更改为 HTML 或富文本,如下所示:

    const type = "text/html"
    const text = "<b>text html</b>";
    const blob = new Blob([text], { type });
    const data = [new ClipboardItem({ [type]: blob })];

    navigator.clipboard.write(data).then(
        () => {alert('success html copy')},
        () => {}
    );
Run Code Online (Sandbox Code Playgroud)

但这不起作用。显示成功警报,但未复制 HTML 文本。

我进行了在线研究,根据我的发现,我的代码似乎是正确的。然而,令人费解的是为什么它没有按预期发挥作用。

顺便说一下,实际上我想创建一个SO片段,但是权限被阻止了,所以如果其他人想尝试我的代码,你检查jsfiddle

Muh*_*kur 6

我找到一篇文章解决了这个问题。

我刚刚意识到,如果我需要同时添加text/plaintext/htmlClipboardItem反对。也许text/plain需要允许系统粘贴为普通格式(cmd/ctrl+shift+v)。

这是正确的代码:

const originalText = "Original Text"
const boldText = "<b>"+originalText+"</b>";
const blobHtml = new Blob([boldText], { type: "text/html" });
const blobText = new Blob([originalText], { type: "text/plain" });
const data = [new ClipboardItem({
    ["text/plain"]: blobText,
    ["text/html"]: blobHtml,
})];

navigator.clipboard.write(data).then(
    () => {alert('success html copy')},
    () => {}
);
Run Code Online (Sandbox Code Playgroud)

您可以在jsfiddle上查看已完成的演示