views:

214

answers:

2

How to set entire HTML in MSHTML?

I am trying using this assignment:

   (Document as IHTMLDocument3).documentElement.innerHTML := 'abc';  

but I got the error:

"Target element invalid for this operation"

I tried also using

(Document as IHTMLDocument2).write 

but this form only adds html into the body section, and I neet to replace all the HTML source.
Does somebody have any idea how I do this?

Thanks in advance.

A: 

Here's some of my old code, see if it helps you:

type
  THackMemoryStream = class(TMemoryStream);

procedure Clear(const Document: IHTMLDocument2);
begin
  Document.write(PSafeArray(VarArrayAsPSafeArray(VarArrayOf([WideString('')]))));
  Document.close;
end;

procedure LoadFromStream(const Document: IHTMLDocument2; Stream: TStream);
var
  Persist: IPersistStreamInit;
begin
  Clear(Document);
  Persist := (Document as IDispatch) as IPersistStreamInit;
  OleCheck(Persist.InitNew);
  OleCheck(Persist.Load(TStreamAdapter.Create(Stream)));
end;

procedure SetHtml(const Document: IHTMLDocument2; const Html: WideString);
var
  Stream: TMemoryStream;
begin
  Stream := TMemoryStream.Create;
  try
    THackMemoryStream(Stream).SetPointer(PWideChar(Html), (Length(Html) + 1) * SizeOf(WideChar));
    Stream.Seek(0, soFromBeginning);
    LoadFromStream(Document, Stream);
  finally
    Stream.Free;
  end;
end;
TOndrej
Thaks. It worked perfect.
Douglas Lise
The correct way to clear the document is to Navigate() to 'about:blank' instead.
Remy Lebeau - TeamB
The problem with Navigate is that it's asynchronous so you'd have to remember/replace the appropriate event handler and restore it later which seems kludgy. I admit I haven't tested the above Clear procedure extensively. Is there a problem with it? An alternative might be to load from an empty (or minimal html string) stream.
TOndrej
A: 

As an alternative you can also use TEmbededWB which is an extended wrapper around a web browser and has some easy to use methods that provide this functionality.

skamradt