[Vue3 + TS + Vite] 将带有HTML样式的文本复制到剪切板

换行分割:硬回车

typescript 复制代码
const copyToClipboardWithStyles = async (html: string) => {
    const modifiedHtml = html.replace(/\n/g, '<br>').replace(/ /g, '&nbsp;')
    const item = new ClipboardItem({
        'text/html': new Blob([modifiedHtml], { type: 'text/html' }),
        'text/plain': new Blob([html], { type: 'text/plain' }),
    })
    if (navigator.clipboard) {
        try {
            await navigator.clipboard.write([item])
        } catch (error) {
            console.error('Failed to copy to clipboard:', error)
        }
    } else {
        console.warn('Your browser does not support writing to the clipboard.')
    }
}

换行分割:段落

typescript 复制代码
const copyToClipboardWithStyles = async (html: string) => {
    const paragraphs = html.split('\n').map(line => `<p>${line.replace(/ /g, '&nbsp;')}</p>`)
    const modifiedHtml = paragraphs.join('')
    const item = new ClipboardItem({
        'text/html': new Blob([modifiedHtml], { type: 'text/html' }),
        'text/plain': new Blob([html], { type: 'text/plain' }),
    })
    if (navigator.clipboard) {
        try {
            await navigator.clipboard.write([item])
        } catch (error) {
            console.error('Failed to copy to clipboard:', error)
        }
    } else {
        console.warn('Your browser does not support writing to the clipboard.')
    }
}
相关推荐
Lee川4 分钟前
从零解剖一个 AI Agent Tool是如何实现的
前端·人工智能·后端
wangruofeng1 小时前
Playwright 深度调研:为什么它成了浏览器自动化的新底座
前端·测试
李白的天不白3 小时前
SSR服务端渲染
前端
XinZong3 小时前
OpenClaw 实现「龙虾」vs 龙虾 vs 用户 ws对话实现方案 + 实际落地项目
javascript
卷帘依旧4 小时前
WebSocket 比 SSE 复杂在哪里
javascript
卷帘依旧4 小时前
SSE(Server-Sent Events)完全指南
前端
码云之上4 小时前
万星入坞:我们如何用三层插件体系干掉巨石应用
前端·架构·前端框架
kyriewen4 小时前
一口气讲清楚 Monorepo、Turborepo、pnpm、Changesets 到底是什么?
前端·架构·前端工程化
logo_285 小时前
Xpath语法规则的学习和使用
javascript·python·xpath·xpath语法
IT_陈寒5 小时前
React性能优化踩的坑,这个错你可能也会犯
前端·人工智能·后端