Skip to content
Advertisement

Copy current URL to clipboard

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.

Advertisement

Answer

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);
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement