As an update to this, I ended up going with this code:
<script>
function copyclip(texttocopy) {
// Create new element
var el = document.createElement('textarea');
// Set value (string to be copied)
el.value = texttocopy;
// Set non-editable to avoid focus and move outside of view
el.setAttribute('readonly', '');
el.style = {position: 'absolute', left: '-9999px'};
document.body.appendChild(el);
// Select text inside element
el.select();
// Copy text to clipboard
document.execCommand('copy');
// Remove temporary element
document.body.removeChild(el);
}
</script>
This creates a temporary hidden element in the DOM to copy from, as opposed to using a permanent element on the page.
This then allows me to pass in a value to be copied, as opposed to having to use a selectable field (e.g. text input) - which means I can copy the value of a label on the page.
def button_1_click(self, **event_args):
self.call_js("copyclip", self.lbl_odscode.text)
I was building a very quick and dirty search page for the National Health Service Organisational Data Service (ODS) https://ods-search.anvil.app
Thanks for the inspiration both @david.wylie and @jshaffstall!