頁面採用 iframe 切分之後,子框架要通知父頁面做事就成了基本需求。寫法只有一行:
window.parent.xxxxx(); // xxxxx() 代表父頁面的方法
下面是一個結合 easyUI 的完整例子,同時示範了右鍵選單與單擊事件的處理。
版面以 easyui-layout 切為左右兩區,左側是樹狀目錄,右側用 iframe 承載內容:
<body class="easyui-layout">
<!-- 左側目錄 -->
<div data-options="region:'west',split:true,title:'主題',iconCls:'icon-arrowIn'"
style="width: 270px; background: #efefef">
<ul id="tree" class="easyui-tree"></ul>
</div>
<input type="hidden" value="${param.type }" id="themeType"/>
<!-- 右側窗體 -->
<div data-options="region:'center',title:'內容顯示',iconCls:'icon-arrowOut'"
style="overflow: hidden">
<iframe name="leftIframe" id="leftIframe" src=""
frameborder="0" height="100%" width="100%"></iframe>
</div>
<!-- 右鍵選單 -->
<div id="rightCliMean" class="easyui-menu" style="width:120px;">
<div onclick="updateTheme();" data-options="iconCls:'icon-edit'">修改</div>
<div onclick="removeObjectNode();" data-options="iconCls:'icon-tip'">刪除</div>
</div>
<script type="text/javascript">
loadTree();
</script>
</body>
樹的建構包含兩個重點:右鍵選單要攔下預設行為並排除根節點,單擊時則依節點型別決定 iframe 載入哪個頁面:
function loadTree() {
$('#tree').tree({
url: 'xxxxx.action',
animate: true,
lines: true,
onContextMenu: function (e, node) {
e.preventDefault(); // 攔掉瀏覽器預設選單
$(this).tree('select', node.target);
// 根節點(預設主題)不允許操作
var parent = $(this).tree('getParent', node.target);
if (parent) {
if (node.text == '默認主題') {
$.messager.alert("提示信息", "默認主題不能進行操作!", "warning");
return false;
}
$('#rightCliMean').menu('show', {
left: e.pageX,
top: e.pageY
});
}
},
onClick: function (node) { // 單擊事件
var type = node.attributes.type;
if ("Schema" == type) {
var themeType = $("#themeType").val();
$('#leftIframe').attr('src', 'xxxx.action');
return;
}
}
});
}
子頁面只需要一行,就能呼叫父頁面剛剛定義的 loadTree 來刷新左側樹:
/** 刷新左側主題 */
$(function () {
window.parent.loadTree();
});
同源限制。window.parent 只能存取與自己同源的框架。一旦 iframe 載入的是跨域頁面,存取 parent 的函式或 DOM 都會丟出安全性錯誤,這時唯一正當的通道是 postMessage。
先確認函式已存在。父頁面的 script 若尚未執行完,子頁面呼叫 window.parent.loadTree() 會得到 undefined 的錯誤。加上 typeof window.parent.loadTree === 'function' 的檢查,或在父頁面 load 完成後主動通知子頁面,都更穩妥。
postMessage 才是跨框架的標準答案。父頁監聽 message 事件、子頁用 parent.postMessage(data, targetOrigin) 傳遞,記得務必驗證 event.origin——若不檢查來源,任何被嵌入的第三方頁面都能對你的父頁發指令,這是常見的安全漏洞。
新專案或許不需要 iframe。上述架構是為了讓 DOM 各自獨立、互不干擾,但在今日以元件化框架搭配前端路由已能達到相同效果,且資料流更清晰。iframe 仍適合用來嵌入真正獨立的系統或第三方內容。