点按钮复制文本,注意非 HTTPS 环境下的限制

navigator.clipboard 只在安全上下文可用,即 HTTPS 或 localhost。

内网 http 站点下它是 undefined,只能退回临时 textarea 方案。

做法是把文本塞进离屏 textarea,选中后调 execCommand('copy'),用完移除节点。

if (navigator.clipboard) {
  await navigator.clipboard.writeText(text)
} else {
  const ta = document.createElement('textarea')
  ta.value = text; document.body.appendChild(ta)
  ta.select(); document.execCommand('copy'); ta.remove()
}
THE END
喜欢就支持一下吧
点赞11 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容