How to set entire HTML in MSHTML?

2019-08-24 17:54发布

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've also tried using

(Document as IHTMLDocument2).write 

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

Thanks in advance.

2条回答
The star\"
2楼-- · 2019-08-24 18:40

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;
查看更多
姐就是有狂的资本
3楼-- · 2019-08-24 18:46

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.

查看更多
登录 后发表回答