很多框架頁面存在父子關係,取值時得一路輾轉,於是常看到這種程式碼:
window.parent.document.getElementById("main")
.contentWindow.document.getElementById('input').value =
document.getElementById('myIframe')
.contentWindow.document.getElementById('s0').value;
框架應用裡有個固定不變的視窗叫 window.top。把資料快取在這個頁面上,其下所有框架都能取到,無論子頁面如何嵌套、如何跳轉。不需要 Cookie,也不需要 HTML5 的本地資料庫策略,只要每個頁面都引用同一支 js 檔:
var share = {
/**
* 跨框架數據共享接口
* @param {String} 存儲的數據名
* @param {Any} 將要存儲的任意數據(無此項則返回被查詢的數據)
*/
data: function (name, value) {
var top = window.top,
cache = top['_CACHE'] || {};
top['_CACHE'] = cache;
return value ? cache[name] = value : cache[name];
},
/**
* 數據共享刪除接口
* @param {String} 刪除的數據名
*/
removeData: function (name) {
var cache = window.top['_CACHE'];
if (cache && cache[name]) delete cache[name];
}
};
寥寥數行就能共享任意型別的資料供各框架頁面讀取,跟頁面名稱、層級無關。哪天框架的嵌套層級被調整,你完全不必擔心。
在 A 頁面存入:
share.data('myblog', 'https://www.jb51.net');
share.data('editTitle', function (val) {
document.title = val;
});
在任意框架頁面取出:
alert('我的博客地址是: ' + share.data('myblog'));
var editTitle = share.data('editTitle');
editTitle('我已經獲取到了數據');
一是不要用 if (value) 判斷,這種寫法有個瑕疵:當你想存入 0、'' 或 false 這類假值時,函式會誤判成「查詢」而回傳舊值。改成 arguments.length > 1 判斷會更嚴謹。
二是同源限制:若某個 iframe 載入了跨域頁面,存取 window.top 的屬性會被瀏覽器阻擋。這種情況仍得回到 postMessage 這類正式方案。
這套技巧在 artDialog 的 iframeTools 擴充裡也能看到類似的身影。