首页 > 解决方案 > 实现复制到剪贴板时处理案例失败和成功

问题描述

我正在尝试在我的项目中实现复制到剪贴板功能。

这是我关于这个函数的代码:

export const copyToClipboard = str => {
  const el = document.createElement('textarea');
  el.value = str;
  document.body.appendChild(el);
  el.select();
  document.execCommand('copy');
  document.body.removeChild(el);
  // I need know when this function executed fail to display notify for the end user.
  // Like: isSuccess ? toast.success("Copy success") : toast.error("Copy fail")
};

那么,执行此功能时如何处理失败或成功?有没有人对这个案子有任何想法?

标签: javascriptdom

解决方案


更喜欢使用剪贴板 API
https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Interact_with_the_clipboard#Using_the_Clipboard_API

export const copyToClipboard = str =>
{
  navigator.clipboard
    .writeText( str )
    .then(_=>{ /* clipboard successfully set */ }
         ,_=>{ /* clipboard write failed */     }
    );
}

推荐阅读