4

Using CEF Browser I try to hook to the OnLoadEnd event in order to traverse the DOM tree.

For some strange reason I get the VisitDom called 2 times.

procedure TForm1.FormCreate(Sender: TObject);
begin
   FBrowser := TChromium.Create(Self);
   FBrowser.Parent := TWinControl(Self);
   FBrowser.OnLoadEnd := BrowserOnLoadEnd;
   FBrowser.Load('http://google.com');
end;

procedure VisitDom(const Document: ICefDomDocument);
begin
  ShowMessage(Document.Document.Name);
end;

procedure TForm1.BrowserOnLoadEnd(Sender: TObject;
  const Browser: ICefBrowser; const Frame: ICefFrame; HttpStatusCode: Integer;
  out Result: Boolean);
var
  Visitor: TCefFastDomVisitor;
begin
  if HttpStatusCode = 200 then
  begin
    Visitor := TCefFastDomVisitor.Create(VisitDom);
    FBrowser.Browser.MainFrame.VisitDom(Visitor);
  end;
end;

Any idea why OnLoadEnd is called multiple times?

Gad D Lord
  • 6,130
  • 10
  • 50
  • 98
  • 1
    may I ask how did you came to the conclusion that "BrowserOnLoadEnd" is called twice? did you put a break point on "begin" or? I haven't used CEF, but I have a strange feeling that this "FBrowser.Browser.MainFrame.VisitDom" is the generator of the "double" event. –  Mar 27 '12 at 22:33
  • P.S. I also see a "out Result: Boolean" shouldn't you make sure that (Result = True)? again, I'm asking not sure.. –  Mar 27 '12 at 22:34
  • Just wondering: why do you cast a TWinControl derived class TForm1 to TWinControl when setting the parent of the browser? That is not ness. (eg the TWinControl(Self); – Ritsaert Hornstra Mar 28 '12 at 09:11
  • I am sure it is called twice since my debugger stop on BrowserOnLoadEnd twice. The Result is always False. – Gad D Lord Mar 28 '12 at 09:26

1 Answers1

5

Seems like OnLoadEnd is called with HttpStatusCode = 200 for each asset the page is having such as: images, external scripts, etc.

The solution is to check for main frame being loaded - Frame.IsMain = True.

if (HttpStatusCode = 200) and Frame.IsMain then
begin
  Visitor := TCefFastDomVisitor.Create(VisitDom);
  FBrowser.Browser.MainFrame.VisitDom(Visitor);
end;
Gad D Lord
  • 6,130
  • 10
  • 50
  • 98