我正在尝试在项目中实现复制到剪贴板功能。
这是我关于此功能的代码:
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")
};
因此,执行此函数时如何处理失败或成功?有谁对此案有任何想法?
首选使用_Clipboard_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 */
});
};