原生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 @ 2022-08-02 17:59  jim520  阅读(1100)  评论(0编辑  收藏  举报