Thursday, April 9, 2009

Using TWebBrowser to display content from stream rather than URL

TWebBrowser is a wrapper for Internet Explorer COM interface. The most common way to use TWebBrowser is using Navigate method that accept a URL string. However, this is not convenient for user who already has a rendered HTML string or stream. One workaround solution for this is save the string or stream to a temporary file and use supply a local file URL to TWebBrowser.Navigate.

Here is a solution for supplying a HTML stream to TWebBrowser:

uses ActiveX;

const IID_IPersistStreamInit : TGUID = '{7FD52380-4E07-101B-AE2D-08002B2EC713}';

procedure TForm19.Button1Click(Sender: TObject);
var S: TStream;
o: IPersistStreamInit;
begin
S := TStringStream.Create('<html><body>this is a test</body></html>');
try
WebBrowser1.Navigate('about:blank');
while WebBrowser1.ReadyState <> Shdocvw.READYSTATE_COMPLETE do
Application.ProcessMessages;

if Supports(WebBrowser1.Document, IID_IPersistStreamInit, o) then
o.Load(TStreamAdapter.Create(S));
finally
S.Free;
end;
end;

No comments: