将当前URL复制到剪贴板

时间:2018-04-02 20:52:11

标签: javascript html clipboard clipboarddata

不知道为什么今天对我这么困难,但由于某种原因我似乎无法将当前的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库)而不使用某种隐藏的文本域。

3 个答案:

答案 0 :(得分:18)

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

不幸的是,剪贴板操作没有标准的API,因此我们采用hacky方式使用HTML input元素来满足我们的需求。我们的想法是创建一个输入,将其值设置为当前文档的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);

答案 1 :(得分:3)

a 19 year old确实是浏览器处理复制时所需要的,而无需任何剪贴板事件的自定义处理。

但是,如果您或某个库挂接到复制事件(例如window.addEventListener('copy', ...),然后如果该处理程序依赖于使用window.getSelection(),那么MDN says Firefox问题将咬住您。就像{ {3}}:

值得注意的是,当前getSelection()在Firefox,Edge(旧版)和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);
}

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

答案 2 :(得分:1)

2021 年更新:您可以像这样使用 Clipboard API

navigator.clipboard.writeText(window.location.href);
相关问题