Question

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?

Was it helpful?

Solution

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;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top