JavaScript - 复制到剪贴板在 Windows 计算机上不起作用

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

我有这个功能,在基于unix的操作系统(Linux,MacOS)中完美工作,但不知何故,在Windows中不起作用,它只是简单地不向剪贴板添加任何内容。

这是在 NextJS 应用程序中运行。

export const copyRichContent = async rich => {

    const html = new Blob([rich], { type: 'text/html' })
    const data = new ClipboardItem({ 'text/html': html })
    await navigator.clipboard.write([data])

}

  • 我已经尝试过使用剪贴板-pollyfill
  • 我在 Windows 中尝试使用 Firefox 和 Chrome
  • 如果我使用 MIME 类型“text/plain”,它就可以工作(但我需要使用 html)

我希望在 Windows 机器上工作,无论浏览器如何。

javascript copy
1个回答
0
投票

I) 首先,使用 https://permission.site/ 检查复制和粘贴功能是否在浏览器中正常工作(在页面底部有剪贴板读/写测试)。如果它不起作用...问题不在您的代码中(您可以打开控制台开发工具以了解更多详细信息)。

II) 考虑安全方面。您的代码必须在安全上下文中运行(https://developer.mozilla.org/en-US/docs/Web/API/Clipboard/write)。主要方面之一是您的页面必须是 HTTPS。但请阅读之前的链接,这是一个很好了解的链接。

III) 在 Windows 上,当您将 text/html 放入剪贴板时,您必须提供 text/plain 替代方案。

看看这个在 Windows 上完美运行的示例:

let button = document.createElement('button')
button.innerText = 'Copy'
button.addEventListener('click', async () => {
    const rich = '<p>Hello <b>world 1</b> and go to <a href="">Link</a>! at ' + Date.now() + '</p>'
    console.log('isSecureContext=', window.isSecureContext)
    const plain = new Blob([rich], { type: 'text/plain' })
    const html = new Blob([rich], { type: 'text/html' })
    const data = new ClipboardItem({ 'text/plain': plain, 'text/html': html })
    await navigator.clipboard.write([data])
})
document.body.append(button)

IV) 请小心用于测试的 RichTextEditor。有些无法正常工作(例如:如果您在写字板中粘贴 HTML,它将无法正常工作)。使用在线 RichTextEditor 来检查。

随时通知我们

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