Copy current URL to clipboard

后端 未结 2 1775
滥情空心
滥情空心 2020-12-15 06:01

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 t

相关标签:
2条回答
  • 2020-12-15 06:31

    ppajer's answer is indeed all that's needed when the browser handles the copying, without any custom handling of clipboard events being involved.

    But if you or some library hook into the copy event (say, window.addEventListener('copy', ...) and then if that handler relies on using window.getSelection(), then a 19 year old Firefox issue will bite you. Like MDN says:

    It is worth noting that currently getSelection() doesn't work on the content of <textarea> and <input> elements in Firefox, Edge (Legacy) and Internet Explorer.

    So, getSelection() returns a non-null result after HTMLInputElement#select, but without providing the actual selected content. Easily fixed by using a non-input element to temporarily hold the 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);
    }
    

    (The above will also work when no custom handler hooks into the copy event.)

    0 讨论(0)
  • 2020-12-15 06:36

    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);
    
    0 讨论(0)
提交回复
热议问题