首页 > 解决方案 > 如何使用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,但它在自动执行时不会复制,用户现在应该始终专注于浏览器。

标签: javascriptvue.js

解决方案


推荐阅读