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);
  savetoclipboard( TLabel( sender ).caption );
  showmessage('Data saved to clipboard!')

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.


  external TClipboard = class( TExternalObject )
     procedure writeText( s : string );

  external TNav2 = class( TNavigator )
     property clipboard : TClipboard read write;

procedure SaveToCLipboard( s : string );
  TNav2(window.navigator).clipboard.writeText( s );

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.