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

为何Android端Chrome中alert()执行后navigator.clipboard.writeText复制失效

问题原因

安卓版Chrome对navigator.clipboard系列API的执行有特殊的安全上下文限制:

  • navigator.clipboard.writeText()属于异步API,调用后不会立即完成剪贴板写入,会进入浏览器的异步任务队列等待执行
  • 安卓Chrome要求剪贴板写入操作必须在*触发操作的用户交互上下文(如点击事件的同步执行周期)*内完成,调用alert()会立刻阻塞当前线程、中断原页面的交互上下文,未执行完成的剪贴板写入任务会被系统直接回收,且不会抛出异常
  • PC端Chrome的剪贴板权限规则更宽松,异步写入任务不受后续alert()阻塞的影响,因此可以正常执行
修复方案

将alert()等后续逻辑放到writeText()的异步回调中,等剪贴板写入完成后再执行:

Promise 写法

function myFunction() {
  var copyText = document.getElementById("myInput");
  copyText.select();
  copyText.setSelectionRange(0, 99999);
  navigator.clipboard.writeText(copyText.value)
    .then(() => {
      alert("Successfully copied the text");
    })
    .catch(err => {
      console.error("复制失败:", err);
    });
}
<input type="text" value="Hello world" id="myInput" style="width:auto">
<button onclick="myFunction()">copy</button>

async/await 写法

async function myFunction() {
  try {
    var copyText = document.getElementById("myInput");
    copyText.select();
    copyText.setSelectionRange(0, 99999);
    await navigator.clipboard.writeText(copyText.value);
    alert("Successfully copied the text");
  } catch (err) {
    console.error("复制失败:", err);
  }
}
<input type="text" value="Hello world" id="myInput" style="width:auto">
<button onclick="myFunction()">copy</button>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 03:06:03