Note: I put up an answer which took the code in the question and altered it just slightly but still used the execCommand in JavaScript but with a warning that this is now (October 2020) obsolete - though available still on many (most) browsers.
This is a more 'modern' way of doing things which falls back on execCommand if necessary. It seems quite complex as we have to check whether the browser's JS supports async and this is done by loading another js file.
Here is the code to put in a file called e.g. new-copy-to-clipboard.js:
async function newCopyToClipboard(text) {
try {
await navigator.clipboard.writeText(text);
} catch (error) { // for when e.g. has been called using http not https
fallbackCopyToClipboard(text);
}
and here is the main js code:
<body>
<button onclick="copyToClipboard('#2E5090')">Copy</button>
<script>
// test whether the browser supports async function declaration or not
new Promise(function (resolve, reject) {
let script = document.createElement('script');
document.body.appendChild(script);
script.onload = resolve.bind(null, true);
script.onerror = reject;
script.async = true;
script.src = 'new-copy-to-clipboard.js';
})
.then(function () {
})
.catch();
function fallbackCopyToClipboard(text) {
let temp = document.createElement('INPUT');
temp.style.position = 'fixed'; //hack to keep the input off-screen...
temp.style.left = '-10000px'; //...but I'm not sure it's needed...
document.body.appendChild(temp);
temp.value = text;
temp.select();
document.execCommand('copy');
//temp.remove(); //...as we remove it before reflow (??)
document.body.removeChild(temp);//to accommodate IE
}
function copyToClipboard(text) {
if (typeof newCopyToClipboard === 'function') {
newCopyToClipboard(text);
}
else {
fallbackCopyToClipboard(text);
}
}
</script>
</body>
}