delphiinternet-explorerdelphi-xe7twebbrowser

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


I have a string var 'HTMLCode' that contains HTML code. I want to load this code into the browser.

This is Embarcadero's code:

procedure THTMLEdit.EditText(CONST HTMLCode: string);
{VAR
   Doc: IHTMLDocument2;
   TempFile: string; }
begin
 TempFile := GetTempFile('.html');  
 StringToFile(TempFile, HTMLCode);
 wbBrowser.Navigate(TempFile);

 Doc := GetDocument;
 if Doc <> NIL
 then Doc.Body.SetAttribute('contentEditable', 'true', 0);  //crash here when I load complex html files

 DeleteFile(TempFile);
end;

It has some problems so I replaced it with this one:

procedure THTMLEdit.EditText(CONST HTMLCode: string);
VAR
   TSL: TStringList;
   MemStream: TMemoryStream;
begin
 wbBrowser.Navigate('about:blank');
 WHILE wbBrowser.ReadyState < READYSTATE_INTERACTIVE
  DO Application.ProcessMessages;

 GetDocument.DesignMode := 'On';

 if Assigned(wbBrowser.Document) then
  begin
    TSL := TStringList.Create;
    TRY
      MemStream := TMemoryStream.Create;
      TRY
        TSL.Text := HTMLCode;
        TSL.SaveToStream(MemStream);
        MemStream.Seek(0, 0);
        (wbBrowser.Document as IPersistStreamInit).Load(TStreamAdapter.Create(MemStream));
      FINALLY
        MemStream.Free;
      end;
    FINALLY
      TSL.Free;
    end;
  end;
end;

But this one has problems also . First, when I insert links (...) into the HTML code, the browser will alter the code, appending 'about:' in front of my URLs. Second: it is slower than the first procedure (the one with temp file).

Can I load HTML code in browser without navigating first to 'about:blank'?


Solution

  • You could load your HTML code as the below

    procedure THTMLEdit.EditText(CONST HTMLCode: string);
    var
      Doc: Variant;
    begin
      if NOT Assigned(wbBrowser.Document) then
        wbBrowser.Navigate('about:blank');
    
      Doc := wbBrowser.Document;
      Doc.Clear;
      Doc.Write(HTMLCode);
      Doc.Close;
    end;