首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

ExtJS 4 TabPanel 中 iframe 刷新的正確姿勢

     編輯:程式設計綜合問答

問題場景

Ext.TabPanel 的項目以 html 配置內嵌 <iframe> 載入 JSP 頁面。嘗試 this.loader.load()、getUpdater().refresh() 等 ExtJS 內建方法均無效,因為 html 配置僅在初始渲染時建立 DOM,後續不受 ExtJS 組件生命週期管理。

核心解法:原生 DOM API 定位 iframe 重載

  1. 為 iframe 指定唯一 id 屬性。
  2. 在需要刷新時 (如 Tab activate 事件、按鈕點擊),透過 document.getElementById 取得 iframe 元素,呼叫 contentWindow.location.reload()。

完整代碼範例

var tabPanel = Ext.create('Ext.TabPanel', {
    id: 'myTabPanel',
    region: 'center',
    layout: 'fit',
    items: [{
        id: 'home',
        title: 'Home Page',
        iconCls: 'House',
        // 關鍵:iframe 加上 id="mainIframe"
        html: '<iframe id="mainIframe" src="jsp/homepage.jsp" width="100%" height="100%" frameborder="0"></iframe>',
        listeners: {
            activate: function(tab) {
                // Tab 啟動時刷新 iframe
                var iframe = document.getElementById('mainIframe');
                if (iframe) {
                    iframe.contentWindow.location.reload();
                }
            }
        }
    }]
});

進階封裝:自訂 IframePanel 組件

Ext.define('MyApp.view.IframePanel', {
    extend: 'Ext.panel.Panel',
    alias: 'widget.iframepanel',
    config: {
        src: '',
        iframeId: null
    },
    html: '<iframe id="{iframeId}" src="{src}" width="100%" height="100%" frameborder="0"></iframe>',
    listeners: {
        afterrender: function(panel) {
            // 動態生成唯一 iframeId
            panel.iframeId = 'iframe_' + Ext.id();
            panel.update(Ext.String.format(panel.html, panel));
        }
    },
    reload: function() {
        var iframe = document.getElementById(this.iframeId);
        if (iframe) iframe.contentWindow.location.reload();
    },
    setSrc: function(src) {
        this.src = src;
        var iframe = document.getElementById(this.iframeId);
        if (iframe) iframe.src = src;
    }
});

// 使用
items: [{
    xtype: 'iframepanel',
    title: 'Home',
    src: 'jsp/homepage.jsp',
    listeners: { activate: 'reload' }
}]

常見坑與注意事項

  • 跨域限制: 若 iframe `src` 與主頁不同源 (協議/域名/埠不同),contentWindow 存取會被瀏覽器阻擋 (SecurityError)。解決:同源部署、或使用 `postMessage` 通訊、或配置 CORS + `document.domain` (僅限同主域)。
  • ExtJS 5/6/7 現代工具包: 推薦使用 Ext.ux.IFrame 組件 (需額外引入),內建 `load()`, `setSrc()`, `getWindow()` 等封裝,避免手動操作 DOM。
  • 記憶體洩漏: Tab 關閉時需確保 iframe 移除,ExtJS `autoDestroy: true` (預設) 會處理,但手動建立的 iframe 需自行 iframe.src = 'about:blank'; iframe.remove();。

總結

ExtJS 組件系統不管理 html 內嵌的原生 iframe 生命週期。**「賦予 iframe ID → 原生 DOM API 操作」是通用、穩健、跨版本的解法**。封裝為可復用組件可大幅提升開發體驗。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved