You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现点击同一按钮同时复制内容到剪贴板并跳转页面?

解决方案

问题出在navigator.clipboard.writeText是异步操作,它返回一个Promise对象。你当前的代码里,复制操作还未完成就立刻执行了页面跳转,浏览器会中断未完成的剪贴板操作,导致复制失败。

你可以通过以下两种方式解决:

方式1:使用async/await

将函数改为异步函数,等待复制操作完成后再执行跳转:

<!DOCTYPE html>
<html>
<body>
<input type="hidden" value={{t}} id="myInput">
<p></p>
<button onclick="myFunction()">Home</button>
<script>
async function myFunction() {
  const copyText = document.getElementById("myInput");
  // 等待剪贴板复制完成
  await navigator.clipboard.writeText(copyText.value);
  // 复制成功后跳转页面
  window.open("my_other_website", "_blank");
}
</script>
</body>
</html>

方式2:使用Promise的.then()回调

如果不想用async/await,也可以通过回调函数等待复制完成:

<!DOCTYPE html>
<html>
<body>
<input type="hidden" value={{t}} id="myInput">
<p></p>
<button onclick="myFunction()">Home</button>
<script>
function myFunction() {
  const copyText = document.getElementById("myInput");
  navigator.clipboard.writeText(copyText.value)
    .then(() => {
      // 复制成功后执行跳转
      window.open("my_other_website", "_blank");
    })
    .catch(err => {
      // 可选:处理复制失败的异常情况
      console.error('复制失败:', err);
    });
}
</script>
</body>
</html>

另外,原代码中的copyText.select()可以去掉,因为navigator.clipboard.writeText直接传入目标值即可完成复制,无需选中输入框。

内容的提问来源于stack exchange,提问作者Hanska

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 10:35:40