Attempt to edit IHTMLDocument hanging application

based on MSHTML documentation for IHTMLDocument2 I'm trying to write a simple HTML parser. Unfortunately, trying to set the editing mode does not work, in other words, resultState never gets a “full” value, so the application freezes.

{$APPTYPE CONSOLE} function ParseHtml(doc: TStringList): TStringList; var iHtml: IHTMLDocument2; v: Variant; msg: tagMSG; begin iHtml := CreateComObject(CLASS_HTMLDocument) as IHTMLDocument2; Result := TStringList.Create; try try iHtml.designMode := 'on'; while iHtml.readyState <> 'complete' do PeekMessage(msg, 0, 0, 0, PM_NOREMOVE); // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // above loop never finishes v := VarArrayCreate([0, 0], varVariant); v[0] := doc.Text; iHtml.write( PSafeArray(TVarData(v).VArray) ); iHtml.designMode := 'off'; while iHtml.readyState <> 'complete' do PeekMessage(msg, 0, 0, 0, PM_NOREMOVE); // processing iHtml.body ... except ... end; finally ... end; ... end; begin CoInitialize(nil); ... CoUninitialize; end. 

Just curious why the readyState property of the IHTMLDocument2 interface is never set to 'complete', although it should be based on official documentation?

+1
source share
2 answers

The readyState property readyState not set to 'complete' because you have not yet told the IHTMLDocument2 object to load the document yet. You must load the document, even a blank one (i.e. the URL 'about:blank' ) in order to affect the readyState property, otherwise it will remain at its initial value of 'uninitialized' .

+4
source

No need to set designMode to on . no need to poll readyState . it will be set to "complete" as soon as you write and close document:

 program Test; {$APPTYPE CONSOLE} uses SysUtils, MSHTML, ActiveX, ComObj; procedure DocumentFromString(Document: IHTMLDocument2; const S: WideString); var v: OleVariant; begin v := VarArrayCreate([0, 0], varVariant); v[0] := S; Document.Write(PSafeArray(TVarData(v).VArray)); Document.Close; end; var Document: IHTMLDocument2; Elements: IHTMLElementCollection; Element: IHTMLElement; begin CoInitialize(nil); Document := CreateComObject(CLASS_HTMLDocument) as IHTMLDocument2; DocumentFromString(Document, '<b>Hello</b>'); Writeln(string(Document.readyState)); // process the Document here Elements := Document.all.tags('b') as IHTMLElementCollection; Element := Elements.item(0, '') as IHTMLElement; Writeln(string(Element.innerText)); Readln; CoUninitialize; end. 
+3
source

All Articles