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

问题描述 投票:0回答:1

基于 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')},
        () => {}
    );

我试过了,效果很好。但我尝试将类型更改为 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

javascript copy clipboard copy-paste navigator
1个回答
1
投票

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

我刚刚意识到,如果我需要同时添加

text/plain
text/html
ClipboardItem
对象。也许需要
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')},
    () => {}
);

您可以在 jsfiddle

© www.soinside.com 2019 - 2024. All rights reserved.