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



基于剪贴板写入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')},
() => {}
);

我试过了,那起作用了。但我尝试将类型更改为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')},
() => {}
);

它不起作用。显示成功提示,但不复制HTML文本。

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

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

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

我刚刚意识到,如果我需要将text/plaintext/html添加到ClipboardItem对象中。也许text/plain需要允许系统粘贴为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')},
() => {}
);

您可以查看工作演示jsfiddle

最新更新