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

4

根据Clipboard Write API specification,我可以像下面这样复制到剪贴板:

    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/plain”类型下的html。不要作为"text/html". - Yosef Tukachinsky
@YosefTukachinsky 我需要复制 HTML 文本或富文本,而不是纯文本。 - Muhammad Dyas Yaskur
1个回答

5

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

我刚刚意识到,如果我需要同时添加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')},
    () => {}
);

您可以在jsfiddle上查看已经运行的演示。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接