頁面中存在多個 iframe,僅 src 屬性不同。需根據 src 值精確選中目標 iframe 並獲取其 contentWindow,而非依賴索引(如 parent.$(".mainFrame")[1])這種脆弱方式。
// 匹配 src 以 "/toProduct" 結尾的 iframe
var targetIframe = parent.$("iframe[src$='/toProduct']");
// 獲取 contentWindow
if (targetIframe.length) {
var win = targetIframe[0].contentWindow;
// 操作 win ...
}
[src$='value']:屬性以 value 結尾(最常用,忽略域名/參數差異)。[src^='value']:屬性以 value 開頭。[src*='value']:屬性包含 value 任意位置。[src='exact']:精確匹配完整 URL。function getIframeWindow(srcSuffix) {
try {
var $iframe = parent.$("iframe[src$='" + srcSuffix + "']");
if ($iframe.length === 0) {
console.warn("未找到 src 結尾為 " + srcSuffix + " 的 iframe");
return null;
}
// 同源策略:僅同域下可訪問 contentWindow
return $iframe[0].contentWindow;
} catch (e) {
console.error("跨域訪問被攔截或 iframe 不存在", e);
return null;
}
}
// 使用
var productWin = getIframeWindow('/toProduct');
if (productWin) productWin.refreshData();
contentWindow,需使用 postMessage 通信。onload 後再查找。[0] 取第一個,建議使用更具體的選擇器(如添加 id 或 class)。使用屬性選擇器根據 src 定位 iframe,比索引方式更健壯、可維護,是多 iframe 頁面交互的標準做法。