javascript - 页面准备好后将文本复制到剪贴板

标签 javascript jquery copy

我试图为用户提供一种在他/她进入页面时自动复制文本的方法。 我可以使用输入和按钮使其工作,如下所示:

<input type="text" id="text-field" value="Some text">
<button onclick="copyToClipboard()"> Copy </button>

这个 js 函数:

const copyToClipboard = str => {
  $('#text-field').select();
  try {
    if (!document.execCommand('copy')) {
      throw false;
    }
    alert('Copied');
  } catch (error) {
    alert('An error has occurred!');
  }
};

当我单击按钮时,文本将被复制。

问题是我想在页面加载时执行此操作。所以,我尝试写这样的东西:

$(function() {
  copyToClipboard();
});

但它显示“已发生!”

有什么办法可以实现这个功能吗?

最佳答案

这是预期的行为。

https://www.w3.org/TR/clipboard-apis/#integration-with-rich-text-editing

Copy and cut commands triggered through a scripting API will only affect the contents of the real clipboard if the event is dispatched from an event that is trusted and triggered by the user, or if the implementation is configured to allow this.

关于javascript - 页面准备好后将文本复制到剪贴板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51875007/

相关文章:

c# - 如何在FTP服务器上复制文件?

javascript - FlipClock 时间值来自 MySQL 数据库,刷新时不重置

javascript - 文档点击不在元素 jQuery

javascript - 将代码声明为 JQuery

javascript - 暂时使元素不可见

javascript - 我可以使用 Angular 将 mouseup 事件绑定(bind)到文档正文吗?

javascript - Mapbox geoJSON 格式化

javascript - Ajax 选项卡设置不适用于本地主机 (EasyTabs)

c# - 将 DataGridView 内容复制到剪贴板

list - 如何在TCL中将列表的某些部分复制到新列表?