Copy current URL to clipboard

穿精又带淫゛_ 提交于 2019-12-30 04:32:05

问题


Not sure why this has been so difficult for me today, but for some reason I cannot seem to get it to copy the current URL to the clipboard. Overall, I'm looking for a way to do it without needing to create some hidden text elements.

This is what I'm trying so far:

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;
});

When I try to go about it using the .select() I get this error: t.select is not a function So I'm not 100% sure what the best way to go about this. Again, without using jQuery (or any other JS library) and not using some sort of hidden textfield.


回答1:


You can create a temporary DOM element to hold the URL

Unfortunately there is no standard API for clipboard operations, so we're left with the hacky way of using a HTML input element to fit our needs. The idea is to create an input, set its value to the URL of the current document, select its contents and execute copy.

We then clean up the mess instead of setting input to hidden and polluting the 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);


来源:https://stackoverflow.com/questions/49618618/copy-current-url-to-clipboard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!