2

I want to find out if the TChromiumFMX browser component contains text that the user has selected, and if so, retrieve that text, without the user having to copy it to the clipboard (ctrl-c) first.


To improve on TLama's answer: If you're not using ShowMessage, the anonymous procedure will not always have completed before Button1Click is exited, hence often yielding no results (or too late). Therefore a Done := true as the last line of the procedure can be checked for to see if the value has been retrieved:

procedure TForm1.Button1Click(Sender: TObject);
var Done: boolean;
begin
  Done := false;
  Chromium1.Browser.GetFocusedFrame.VisitDomProc(
    procedure(const document: ICefDomDocument)
    begin
      SelectedText := document.SelectionAsText;
      Done := true
    end
  );
  while not Done do Application.ProcessMessages
end;
Domus
  • 1,263
  • 7
  • 23

1 Answers1

5

You will have to visit DOM, and as a gift you'll receive a reference to the current ICefDomDocument document interface. The ICefDomDocument interface then offers the SelectionAsText method, which returns the current selection as text (if any). In code you may write something like:

procedure TForm1.Button1Click(Sender: TObject);
begin
  Chromium1.Browser.GetFocusedFrame.VisitDomProc(
    procedure(const document: ICefDomDocument)
    begin
      ShowMessage(document.SelectionAsText);
    end
  );
end;
TLama
  • 75,147
  • 17
  • 214
  • 392
  • Wow, that was quick! Works like a charm. Thanks! – Domus Nov 13 '13 at 01:47
  • I've updated my question to contain the answer, with a little improvement. Feel free to cut it out of the question and paste it into the answer. – Domus Nov 13 '13 at 16:49
  • Is there anyway of doing this in Delphi 7, as it does not have annonymous methods, and I try replacing it with a normal procedure but it does not seem to get called. – altazu Sep 09 '14 at 08:12
  • @altazu, using a regular procedure should work and I'm afraid that you're a victim of a DCEF (maybe CEF, don't know that for sure) version where DOM visiting doesn't work at all (that was the main reason why I've stopped using DCEF). I haven't ever dig into the source of the problem, so I can't help you with this further. Here is one question with the [`same problem`](http://stackoverflow.com/q/14470176/960757) (but I remember there was more of them). – TLama Sep 09 '14 at 08:30
  • Thanks for that. Looks like I'm stuffed. Do you know of any alternatives to the inbuild web browser or chromium. – altazu Sep 09 '14 at 09:05
  • @altazu, there is e.g. the Chromium [`WACEF wrapper`](https://bitbucket.org/WaspAce/wacef) which seems to be still alive (last commit 4 days ago since now) but I'm having almost no experience with it. With other embedded browsers I've no experience at all. Maybe you can take a look at [`this question`](http://stackoverflow.com/q/162718/960757) which is quite outdated but maybe you'll find something useful there. – TLama Sep 09 '14 at 09:14