解决http下navigator.clipboard为undefined的问题
clipboard只有在安全域名下才可以访问(https、localhost), 而http域名下只能得到undefined。
例如现在想要实现点击"分享"按钮,将当前页面的url复制到剪贴板:
const clipboard = navigator.clipboard
if (clipboard) {
clipboard.writeText(window.location.href)
}
在本地localhost测试是可以的,但是部署到服务器上后,由于部署的服务器使用的是http协议,所以clipboard为undefined。
解决方法:
可以考虑使用document.execCommand('copy')
来实现复制到剪贴板的功能。
创建input写入待复制的文本,选定文本后执行document.execCommand('copy')
进行复制:
const clipboard = navigator.clipboard || {
writeText: (text) => {
const input = document.createElement('input')
input.value = text
document.body.appendChild(input)
input.select()
document.execCommand('copy')
document.body.removeChild(input)
}
}
if (clipboard) {
clipboard.writeText(window.location.href)
}
也可以使用document.execCommand('copy')
触发复制事件后,再在复制事件中对剪贴板进行操作:
export default {
methods: {
share() {
this.isShare = true
document.execCommand('copy')
setTimeout(() => { this.isShare = false }, 100)
}
},
created () {
this.copyListener = (event) => {
if (!this.isShare) { return }
const clipboardData = event.clipboardData || window.clipboardData
clipboardData.setData('text', window.location.href)
event.preventDefault()
}
window.addEventListener('copy', this.copyListener)
},
beforeDestroy () {
window.removeEventListener('copy', this.copyListener)
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具