30

不知道为什么今天这对我来说如此困难,但由于某种原因,我似乎无法将当前 URL 复制到剪贴板。总的来说,我正在寻找一种不需要创建一些隐藏文本元素的方法。

到目前为止,这是我正在尝试的:

var shareBtn = document.querySelector(".share-button");

shareBtn.addEventListener('click', function(event) {
  var cpLink = window.location.href;
  cpLink.select();

  try {
    var successful = document.execCommand('copy');
    var msg = successful ? 'successful' : 'unsuccessful';
    console.log('Copy command was ' + msg);
  } catch (err) {
    console.log('Oops, unable to copy');
  }
  event.preventDefault;
});

当我尝试使用它来解决这个问题时,.select()我收到了这个错误: t.select is not a function 所以我不是 100% 确定最好的方法是什么。同样,不使用 jQuery(或任何其他 JS 库)并且不使用某种隐藏的文本字段。

4

4 回答 4

79

您可以创建一个临时 DOM 元素来保存 URL

不幸的是,没有用于剪贴板操作的标准 API,因此我们只能采用一种使用 HTMLinput元素来满足我们需求的骇人听闻的方式。这个想法是创建一个输入,将其值设置为当前文档的 URL,选择其内容并执行copy.

然后我们清理混乱,而不是将输入设置为隐藏并污染 DOM。

var dummy = document.createElement('input'),
    text = window.location.href;

document.body.appendChild(dummy);
dummy.value = text;
dummy.select();
document.execCommand('copy');
document.body.removeChild(dummy);
于 2018-04-02T21:17:56.310 回答
22

2021 年更新:您可以像这样使用剪贴板 API

navigator.clipboard.writeText(window.location.href);
于 2021-04-26T18:56:45.903 回答
4

当浏览器处理复制时, ppajer 的答案确实是所有需要的,而不涉及对剪贴板事件的任何自定义处理。

但是,如果您或某些库挂钩到复制事件(例如,window.addEventListener('copy', ...)然后如果该处理程序依赖于 using window.getSelection(),那么一个 19 岁的Firefox 问题会咬你。就像MDN 说的:

值得注意的是,目前getSelection()不适用于 Firefox、Edge (Legacy) 和 Internet Explorer 中的内容<textarea><input>元素。

因此,getSelection()在 之后返回非空结果HTMLInputElement#select,但不提供实际选择的内容。通过使用非输入元素临时保存 URL 可以轻松修复:

function copyUrl() {
  if (!window.getSelection) {
    alert('Please copy the URL from the location bar.');
    return;
  }
  const dummy = document.createElement('p');
  dummy.textContent = window.location.href;
  document.body.appendChild(dummy);

  const range = document.createRange();
  range.setStartBefore(dummy);
  range.setEndAfter(dummy);

  const selection = window.getSelection();
  // First clear, in case the user already selected some other text
  selection.removeAllRanges();
  selection.addRange(range);

  document.execCommand('copy');
  document.body.removeChild(dummy);
}

(当没有自定义处理程序挂钩到复制事件时,上述内容也将起作用。)

于 2020-08-03T08:50:55.017 回答
2

window.navigator.clipboard.writeText(textToCopy);

于 2021-10-19T04:11:55.863 回答