delphitchromium

TChromium OnClick


I want to track how many clicks the user did inside TChromium. I don't care if he clicks in a "white space"/link/button/image/etc.. I just want to know how many clicks he did. I was hoping there is Onclick event in TChromium but there is none. How can I know if the user clicks?


Solution

  • You can add an event listener. The problem here is that CEF3 doesn't support DOM event listeners like CEF1 did, so it's not that easy there (not impossible though). One quite dirty workaround before I try to craft a V8 interaction example can be this. You create a unique enough string, add an event listener for the whole document, and in this event you log the message with that unique string. And in Delphi you'll be waiting for that unique log message, e.g.:

    const
      MyClickMessage = '08B52B44-748F-44BB-AC6C-5179D6C1F523';
    
    procedure TForm1.Chromium1LoadEnd(Sender: TObject; const browser: ICefBrowser;
      const frame: ICefFrame; httpStatusCode: Integer);
    begin
      if frame.IsMain then
        frame.ExecuteJavaScript(
          'document.addEventListener("click", function(evnt){' +
              'console.log("' + MyClickMessage + '");' +
          '});',
          '',
          0);
    end;
    
    procedure TForm1.Chromium1ConsoleMessage(Sender: TObject; const browser: ICefBrowser;
      const message, source: ustring; line: Integer; out Result: Boolean);
    begin
      if message = MyClickMessage then
      begin
        Result := True;
        ShowMessage('User clicked!');
      end;
    end;
    

    Hacky, right :)? I'll try to come up with something better (using V8 engine)..