对页面进行复制的时候,使用 navigator.clipboard 有限制,有 window.isSecureContext 参数来用于判断,在 true 的情况下(https 或者 localhost),可以直接使用,在 false 或者不支持的老旧浏览器,需要做 polifill。
const codeToCopy = 'hello'async copyCode () {if (typeof navigator.clipboard === 'undefined') {const textArea = document.createElement('textarea')textArea.value = codeToCopytextArea.style.position = 'fixed'document.body.appendChild(textArea)textArea.focus()textArea.select()try {const successful = document.execCommand('copy')const msg = successful ? '复制成功' : '复制失败'toast.info(msg)} catch (err) {toast.info(err)}document.body.removeChild(textArea)} else {try {await navigator.clipboard.writeText(codeToCopy)} catch (err) {toast.info(err)}}}
