Copy current URL to clipboard

后端 未结 2 1784
滥情空心
滥情空心 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: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);
    

提交回复
热议问题