Copy current URL to clipboard

2021 update: you can use the Clipboard API like so:

navigator.clipboard.writeText(window.location.href);

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);