1

I need to write function that would copy the current URL in address bar to the clipboard.

Before you put this to duplicate, read me out:

I want to dynamically copy to clipboard, not when user triggers the copy event (as some other answers suggest: How do I copy to the clipboard in JavaScript?)

By now, I did it this way:

function copyAddressBarToClipboard() {  
    var input = document.createElement('input');
    document.body.appendChild(input);    
    input.value = window.location.href;    
    input.select();
    document.execCommand('copy');
    document.body.removeChild(input);   
}

<button onclick="copyAddressBarToClipboard()">copyAddressBarToClipboard</button>

However, the document.execCommand seems to be obsolete (https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand) so I need to find more adequate solution.

Dalibor
  • 1,430
  • 18
  • 42
  • https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API `document.execCommand` will probably stick in browsers forever, though, removing it would break the internet. Note also, that `location.href` doesn't necessarily contain the exact content of the address bar. – Teemu Jan 15 '21 at 09:02
  • https://stackoverflow.com/questions/60581285/execcommand-is-now-obsolete-whats-the-alternative is an good answear of the question about execCommand. And you can take a look to the Clipboard API: https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API – Maik Lowrey Jan 15 '21 at 09:05

1 Answers1

0

Good question! Here a small script which use the clipboard API. But remember the clipboard Api is available since Chrome 66.

HTML

<input id="input" value="Hello World">
<button id="copy">Copy Text</button>

JS

document.querySelector('#copy').addEventListener('click', () => {
  navigator.clipboard.writeText(document.querySelector('#input').value)
    .then(() => {
      alert('Text copied.');
    })
    .catch(() => {
      Alert('Failed ');
    });
});

I hope i useful and helps a little.

Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79