对页面进行复制的时候,使用 navigator.clipboard 有限制,有 window.isSecureContext 参数来用于判断,在 true 的情况下(https 或者 localhost),可以直接使用,在 false 或者不支持的老旧浏览器,需要做 polifill。

    1. const codeToCopy = 'hello'
    2. async copyCode () {
    3. if (typeof navigator.clipboard === 'undefined') {
    4. const textArea = document.createElement('textarea')
    5. textArea.value = codeToCopy
    6. textArea.style.position = 'fixed'
    7. document.body.appendChild(textArea)
    8. textArea.focus()
    9. textArea.select()
    10. try {
    11. const successful = document.execCommand('copy')
    12. const msg = successful ? '复制成功' : '复制失败'
    13. toast.info(msg)
    14. } catch (err) {
    15. toast.info(err)
    16. }
    17. document.body.removeChild(textArea)
    18. } else {
    19. try {
    20. await navigator.clipboard.writeText(codeToCopy)
    21. } catch (err) {
    22. toast.info(err)
    23. }
    24. }
    25. }