javascript - 实现复制到剪贴板时处理案例失败和成功
问题描述
我正在尝试在我的项目中实现复制到剪贴板功能。
这是我关于这个函数的代码:
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")
};
那么,执行此功能时如何处理失败或成功?有没有人对这个案子有任何想法?
解决方案
更喜欢使用剪贴板 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 */ }
);
}
推荐阅读
- java - 大量创建石英触发器
- r - 目标“sysdata”的配方失败 - 不允许负长度向量(编译 R-cran v4.0.0)
- rust - Rust:impl trait 不能在线程之间安全共享
- visual-studio-code - Coffeescript 的 VSCode 语法高亮显示似乎不完整
- python - 正则表达式根据特定字符串提取日期
- javascript - JSON解析decodedURI失败?
- arrays - 替换数组中的索引
- flutter - 在 LIGHT 和 DARK 主题之间切换 (flutter_neumorphic: ^2.0.0)
- firebase - 监控 Firestore 中存储的数据大小
- android-recyclerview - 如何确认recyclerview项目列表中的选定项目并在布局上进行选择