javascript - 如何使用javascript自动复制从api收到的包含链接的文本
问题描述
我正在尝试在应用程序中实现一项功能,该功能允许用户在成功处理请求时将文本自动复制到剪贴板,但是在这些文本中的链接方面存在一些问题。
我正在尝试构建一个文本区域来复制和使用 document.execCommand
copy(str) {
const el = document.createElement('textarea');
el.value = str;
el.setAttribute('readonly', '');
el.style.position = 'absolute';
el.style.left = '-9999px';
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);
}
在请求上下文中,它看起来像这样
async function submit() {
this.$confirm({
message: `Are you sure?`,
button: {
no: 'No',
yes: 'Yes',
},
callback: async (confirm) => {
if (confirm) {
// loader
const loader = this.$vs.loading({
target: this.$refs.container,
type: 'scale',
});
try {
const res = await this.$axios.post('/api/run');
try {
this.$globals.copy(res.text);
} catch (err) {
console.error(err);
this.$vs.notification({
color: 'warning',
position: 'top-right',
title: 'Could not automatically copy',
});
}
} catch (err) {
console.error(err);
this.$vs.notification({
color: 'danger',
position: 'top-right',
duration: 120000,
title: 'Error',
text: err.response
? err.response.data.message
: 'Failed to process the request',
});
} finally {
loader.close();
}
}
},
});
}
问题是如果它包含链接,它不会复制背景上的文本(当窗口没有聚焦,或其他应用程序打开时),我已经测试了几次并且可以确认。我也尝试过navigator.writeText
,但它在自动执行时不会复制,用户现在应该始终专注于浏览器。
解决方案
推荐阅读
- javascript - 如果内容量不固定,如何在特定滚动后隐藏 div?
- android - 为什么在 Android ContentProvider 中我不能使用像 'this' 这样的上下文而不是 getContext()
- c# - Azure Vault 在本地运行
- java - 在 Springboot Java 中维护键值映射对的最佳方法
- android - 无法理解 () -> 调用
- r - 如何为 R 中的每一列创建一个单独的数据框,然后将所有栅格图层栅格化并将其绑定到多层栅格中?
- azure - 扩展 Azure SQL 弹性池存储时是否存在停机时间?
- php - 如何使用多个 php-fpm docker 容器设置单个 nginx 服务器
- flutter - 如何将小部件嵌入图像并将其保存到设备
- java - 使用 Apache POI HSSF 在 Excel 中存储 ArrayList