原生JS实现复制功能(document.execCommand 和 navigator.clipboard.writeText)

因为document.execCommand('copy')已弃用 

所以我们需使用 异步剪贴板 API [navigator.clipboard.writeText]

代码如下:

复制代码
function fallbackCopyTextToClipboard(id: string) {
  const range: any = document.createRange();
  range.selectNode(document.getElementById(id));
  const selection: any = window.getSelection();
  if (selection.rangeCount > 0) selection.removeAllRanges();
  selection.addRange(range);
  try {
    const successful = document.execCommand('copy'); //复制选中的文字到剪贴板
    selection.removeRange(range); // 移除选中的元素
    var msg = successful ? 'successful' : 'unsuccessful';
    console.log('Fallback: Copying text command was ' + msg);
    return msg;
  } catch (err) {
    selection.removeRange(range);
    console.error('Fallback: Oops, unable to copy', err);
    return false;
  }
}

export function copyTextToClipboard(id: string) {
  if (!navigator.clipboard) {
    return fallbackCopyTextToClipboard(id);
  }
  const range: any = document.createRange();
  range.selectNode(document.getElementById(id));
  const selection: any = window.getSelection();
  if (selection.rangeCount > 0) selection.removeAllRanges();
  selection.addRange(range);
  return navigator.clipboard.writeText(selection).then(function () {
    selection.removeRange(range);
    console.log('Async: Copying to clipboard was successful!');
    return 'successful';
  }, function (err) {
    selection.removeRange(range);
    console.error('Async: Could not copy text: ', err);
    return false;
  });
}
复制代码

 

posted @   jim520  阅读(1132)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示