在 Delphi 中使用 TWebBrowser 控件進行網頁自動化或內容處理時,核心在於操作 MSHTML DOM 模型。IHTMLDocument 系列接口(從 IHTMLDocument2 到 IHTMLDocument5)提供了對文檔結構、樣式、選區、事件等全方位的控制能力。本文系統整理了這些接口的方法、屬性與事件,供開發者快速查閱與實戰參考。
作為最基礎且常用的文檔接口,IHTMLDocument2 涵蓋了文檔流控制、元素集合訪問、樣式表管理、命令執行等核心功能。
write 內容,關閉並輸出流。queryCommandSupported、Enabled、State、Indeterm、Text、Value,用於檢查編輯命令狀態。提供對各類元素的集合式訪問:
all:所有元素集合images、applets、links、forms、anchors、scripts、frames、embeds、plugins、styleSheetstitle、body、activeElement、designMode、selection、readyStatelinkColor、alinkColor、vlinkColor、bgColor、fgColorreferrer、location、url、domaincookie、charset、mimeType、fileSize、security、protocol、parentWindow涵蓋滑鼠、鍵盤、選區、拖放、數據綁定、錯誤處理等:onclick、ondblclick、onmousedown/up/move/over/out、onkeypress/down/up、onreadystatechange、onselectstart、ondragstart、onbeforeupdate/afterupdate/errorupdate 等。
recalc:重新計算動態屬性releaseCapture:釋放滑鼠捕獲createTextNode、attachEvent/detachEvent、createDocumentFragmentgetElementsByName、getElementById、getElementsByTagNamedocumentElement(根節點)、uniqueID、dir、parentDocument、baseUrl數據綁定相關:onrowsdelete、onrowsinserted、oncellchange、ondatasetchanged、ondataavailable、ondatasetcomplete、onpropertychange、oncontextmenu、onstop。
focus / hasFocus:焦點控制createDocumentFromUrl:下載並返回文檔接口CreateEventObject / FireEvent:自定義事件觸發createRenderStyle、namespaces、media、URLUnencodedonselectionchange、oncontrolselectcreateAttribute、createCommentdoctype、implementation_、compatMode(返回 BackCompat 或 CSS1Compat)onmousewheel、onfocusin/out、onactivate/deactivate、onbeforeactivate/beforedeactivateMSHTML 單元,介面變量聲明為 IHTMLDocument2 以上類型。(WebBrowser1.Document as IHTMLDocument2) 獲取接口實例。attachEvent/detachEvent 而非直接賦值,避免覆蓋現有處理程序。designMode = 'On' 可開啟所見即所得編輯模式,配合 execCommand 實現富文本編輯器。掌握這些接口細節,能讓你在 Delphi 中像操作 JavaScript DOM 一樣靈活控制網頁內容,構建強大的網頁自動化、內容提取、測試工具或嵌入式瀏覽器應用。