简体   繁体   中英

Javascript - copy some text dynamically to the clipboard

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM