kyo*_*kyo 57 javascript copy-paste vue.js vue-component vuejs2
我有一个按钮
当我点击复制时
copyImageLinkText({ mouseenter, mouseleave }, e) {
this.showCopiedText = !this.showCopiedText
navigator.clipboard.writeText(this.imageLink)
clearTimeout(this._timerId)
mouseenter(e)
this._timerId = setTimeout(() => mouseleave(e), 1000)
},
Run Code Online (Sandbox Code Playgroud)
这条线似乎在我的 MacBook Pro 上本地运行得很好
navigator.clipboard.writeText(this.imageLink)
Run Code Online (Sandbox Code Playgroud)
当我构建并将其部署到我的开发服务器时,它不起作用。
类型错误:无法读取未定义的属性(读取“writeText”)
Ali*_*cia 118
指某东西的用途navigator.clipboard
需要安全来源。因此,如果您的开发环境通过 HTTP 提供服务,则剪贴板方法将不可用。
根据MDNClipboard
文档
\n\n此功能仅在安全上下文(HTTPS)、部分或所有支持的浏览器中可用。
\n
也许您可以检查此方法是否可用window.isSecureContext
,并相应地禁用“复制文本”按钮。
最好的选择是在您的开发环境中使用 HTTPS。
\n但既然您要求解决方法,这里有一个(非常黑客的)工作方法。使用Document.exec
不再推荐的命令,有利于ClipboardAPI
.
function unsecuredCopyToClipboard(text) {\n const textArea = document.createElement("textarea");\n textArea.value = text;\n document.body.appendChild(textArea);\n textArea.focus();\n textArea.select();\n try {\n document.execCommand(\'copy\');\n } catch (err) {\n console.error(\'Unable to copy to clipboard\', err);\n }\n document.body.removeChild(textArea);\n}\n
Run Code Online (Sandbox Code Playgroud)\n然后您可以检查是否!navigator.clipboard
并调用后备方法,否则继续正常操作navigator.clipboard.writeText(...)
功能。例如:
const unsecuredCopyToClipboard = (text) => { const textArea = document.createElement("textarea"); textArea.value=text; document.body.appendChild(textArea); textArea.focus();textArea.select(); try{document.execCommand(\'copy\')}catch(err){console.error(\'Unable to copy to clipboard\',err)}document.body.removeChild(textArea)};\n\n/**\n * Copies the text passed as param to the system clipboard\n * Check if using HTTPS and navigator.clipboard is available\n * Then uses standard clipboard API, otherwise uses fallback\n*/\nconst copyToClipboard = (content) => {\n if (window.isSecureContext && navigator.clipboard) {\n navigator.clipboard.writeText(content);\n } else {\n unsecuredCopyToClipboard(content);\n }\n};
Run Code Online (Sandbox Code Playgroud)\r\n<button onClick="buttonPress()">\xe2\x9e\xa1\xef\xb8\x8f Copy Message to Clipboard</button>\n\n<script type="text/javascript"> const buttonPress = () => { copyToClipboard(\'Hello World!\'); console.log(\'Clipboard updated \\nNow try pasting!\'); }; </script>
Run Code Online (Sandbox Code Playgroud)\r\n 归档时间: |
|
查看次数: |
59313 次 |
最近记录: |