Copying a TLabel to the Clipboard
All modern browsers support the Clipboard with the following technique. It may not work on Internet Explorer, but that ship has sailed over the edge and it’s not worth supporting.
Often you will want to allow users to copy text from a label (or other component). It’s possible to configure TLabels to have an onClick handler which automatically copies to the Clipboard.
procedure TFormReportDropsAdds.Label2Click(Sender: TObject); begin savetoclipboard( TLabel( sender ).caption ); showmessage('Data saved to clipboard!') end;
Now all we need to do is call the API.
A quick web search will show you the JavaScript call is:
navigator.clipboard.writeText( string );
But this is EWB, we need a bit of housekeeping. Navigator is under the window global, and clipboard isn’t defined.
So we need to have a definition for these things earlier in the file.
type external TClipboard = class( TExternalObject ) public procedure writeText( s : string ); end; external TNav2 = class( TNavigator ) public property clipboard : TClipboard read write; end; procedure SaveToCLipboard( s : string ); begin TNav2(window.navigator).clipboard.writeText( s ); end;
I’d suggest setting the font format underline flag to make the clip option obvious to your users. And you can throw in a ShowMessage(`Copied to clipboard.'); message.
Note: clipboard often won’t work if the site is HTTP, it must be HTTPS.