首页 > 解决方案 > HTML 复制到剪贴板按钮不起作用

问题描述

我正在尝试做一个按钮来将链接(www.google.com)复制到剪贴板,但它不起作用。我的代码是:

<script type='text/javascript'>
    function myFunction() {
      /* Get the text field */
      var copyText = document.getElementById("www.google.com");
    
      /* Select the text field */
      copyText.select();
      copyText.setSelectionRange(0, 99999); /* For mobile devices */
    
       /* Copy the text inside the text field */
      navigator.clipboard.writeText(copyText.value);
    
      /* Alert the copied text */
      alert("Copied link!");
    }
</script>

和按钮:

<button onclick='myFunction()'>Clik to copy the Link</button>

标签: javascripthtml

解决方案


尝试使用异步功能并等待

async function copyGoogleLink(){
    await navigator.clipboard.writeText('https://www.google.com')
    .then(() => console.log('Copied'));
}

将此与事件侦听器一起使用


推荐阅读