pc和移动端浏览器复制文字至手机粘贴板

发布于 2024-07-12  250 次阅读


部分pc端浏览器支持navigator.clipboard.writeText(text);

大部分移动端仅支持document.execCommand(‘copy’) 复制方法

   const copyText = async ()=>{
        let text = '需要复制的文本';
 try {
    await navigator.clipboard.writeText(text);
    // console.log('内容已复制到剪贴板');
    showSuccessToast('内容已复制到剪贴板');

  } catch (err) {
    console.log("err")
    // console.error('复制到剪贴板失败', err);
    try{
      var textArea = document.createElement("textarea");
      textArea.value = text;
      textArea.style.position = "fixed";
    textArea.style.opacity = 0;
    textArea.style.left = "-999999px";
    textArea.style.top = "-999999px";
    document.body.appendChild(textArea);
    // textArea.focus();
    textArea.select();
    showSuccessToast('内容已复制到剪贴板2');
    return new Promise((res, rej) => {
      // 执行复制命令并移除文本框
      document.execCommand('copy') ? res() : rej();
      textArea.remove();
    });

    }catch(err2){
   console.log("err2");
   console.log(err2)
   showFailToast('复制到剪贴板失败,设备不支持访问粘贴板');

    }
  }
   }

一沙一世界,一花一天堂。君掌盛无边,刹那成永恒。