IE BHO 中 IHTMLDocument2 僅代表主文檔,<iframe> 內容屬於獨立文檔上下文,需額外跨框架存取。
IHTMLFramesCollection2 frames = (IHTMLFramesCollection2)doc.frames;
for (int i = 0; i < frames.length; i++) {
var frameWindow = (IHTMLWindow2)frames.item(i);
var frameDoc = (IHTMLDocument2)frameWindow.document;
// 在 frameDoc 中查找元素
}
注意:跨域 iframe 會拋「存取被拒」,需 try-catch 忽略。
string script = @"
(function() {
var els = document.querySelectorAll('your-selector');
var result = [];
for (var i=0;i<els.length;i++) result.push(els[i].outerHTML);
return JSON.stringify(result);
})();
";
object result = frameWindow.execScript(script, "JavaScript");
// 解析 JSON 字串
優點:繞過跨域限制(同源策略下同域可執行)、邏輯集中在 JS 端靈活。