2

This question is related to: Which is the best way to load a string (HTML code) in TWebBrowser?

Iam trying to change font in TWebBrowser with doc.body.style.fontFamily but nothing happens. The font is still TimesNewRoman.

procedure THTMLEdit.SetHtmlCode(CONST HTMLCode: string);
VAR
   Doc: Variant;
begin
 if NOT Assigned(wbBrowser.Document)
 then wbBrowser.Navigate('about:blank');

 WHILE wbBrowser.ReadyState < READYSTATE_INTERACTIVE
   DO Application.ProcessMessages;

 Doc := wbBrowser.Document;
 Doc.Clear;
 Doc.Write(HTMLCode);
 doc.body.style.fontFamily:='Arial'; <------ won't work
 Doc.DesignMode := 'On';
 Doc.Close;
end;
Community
  • 1
  • 1
Gabriel
  • 20,797
  • 27
  • 159
  • 293
  • It depends on the content of the page, how it is styled. There won't be a single solution. Do you have control over the content of the page, or can it be arbitrary?# – David Heffernan Jan 31 '17 at 12:03
  • The content is created in TWebBrowser and not imported from a HTML page. The user will enter basic formatting such as bold, bullets, etc. So, the content has no , , css, etc. – Gabriel Jan 31 '17 at 12:59

1 Answers1

5

You need to let the document be interactive again after you close the document. e.g.:

procedure TForm1.SetHtmlCode(CONST HTMLCode: string);
VAR
   Doc: Variant;
begin
  if NOT Assigned(wbBrowser.Document)
  then wbBrowser.Navigate('about:blank');

  //WHILE wbBrowser.ReadyState < READYSTATE_INTERACTIVE // not really needed
  //DO Application.ProcessMessages;

  Doc := wbBrowser.Document;
  //Doc.Clear; // not needed
  Doc.Write(HTMLCode);
  Doc.Close; 
  Doc.DesignMode := 'On';

  WHILE wbBrowser.ReadyState < READYSTATE_INTERACTIVE
  DO Application.ProcessMessages;

  doc.body.style.fontFamily:='Arial';

  ShowMessage(doc.body.outerHTML); // test it
end;

But I think the best way is to handle the OnDocumentComplete where you know you have a valid document/body, and set the style or what ever else needed.

kobik
  • 21,001
  • 4
  • 61
  • 121
  • Like a charm. MANY THANKS. You are really good with TWebBrowser. – Gabriel Jan 31 '17 at 13:07
  • I know I should not use ProcessMessages. I am too lazy/in a hurry to implement OnDocumentComplete now. But I promisse I will do it :) – Gabriel Jan 31 '17 at 13:08
  • 3
    You are welcome. `TWebBrowser` is processing asynchronously and event driven. switching to `OnDocumentComplete` will eventually make your life easier, and (hopefully) bug free. – kobik Jan 31 '17 at 13:16