Programming Delphi How to use TWebBrowser to load a document from memory(from a string)?
Notice: Undefined variable: relatedArticlesCount in /home/wwwroot/codeback.net/plugins/content/tags.php on line 149

We konw that use the TWebBrowser to load a html file is easy by the Navigate funtion. While sometimes we need to load a variant string(html formate of contents) from the memory and show it on the webbrowser. Of course you can do it by saving the string to temporary html file and then loading it. Yet this method seens not so good. Here is a better way to do that, also it could get a faster speed.

Create a new project, drag a TWebBrowser component onto the form. Adding a procedure named loadStringHtml showed below and adding the shows code in the onFormCreate event.

procedure loadStringHtml(WebBrowser: TWebBrowser; HTMLCode: string) ;
var
   strList:   TStringList;
   memStream: TMemoryStream;
begin
   WebBrowser.Navigate('about:blank') ;
   while WebBrowser.ReadyState < READYSTATE_INTERACTIVE do
    Application.ProcessMessages;

   if Assigned(WebBrowser.Document) then
   begin
     strList := TStringList.Create;
     try
       memStream := TMemoryStream.Create;
       try
         strList.Text := HTMLCode;
         strList.SaveToStream(memStream) ;
         memStream.Seek(0, 0) ;
         (WebBrowser.Document as IPersistStreamInit).Load(TStreamAdapter.Create(memStream)) ;
       finally
         memStream.Free;
       end;
     finally
       strList.Free;
     end;
   end;
end;

procedure TForm1.FormCreate(Sender: TObject) ;
var
  strHtml : string;
begin
   strHtml='Programer's Home--CodeBack.NET';
   loadStringHtml(WebBrowser1,strHtml) ;
end; 

Run the project to see what happen! Enjoy your job.


Add comment


Security code
Refresh

Programming - Delphi