需求背景
假設有 a.html 與 b.html 兩個純靜態頁面,要處理兩件事:
前提同樣是不涉及跨域。
a 頁面負責送出:
<button>跳轉設置</button>
<script>
var btn = document.querySelector('button');
console.log(window);
btn.addEventListener('click', function(){
window.location = 'ci.html#bgc=#369?wd=500'
})
</script>
按下按鈕後會跳轉,網址尾端多出一串參數。由於這些內容位於 # 之後,不會進入 HTTP 請求,對伺服器完全透明,卻能被下一頁讀取。
b 頁面負責接收:
<div></div>
<script>
var div = document.querySelector('div');
var bl = window.location.hash.slice(1).split('?');
if (bl.length >= 1) {
for (var i = 0; i < bl.length; i += 1) {
switch (bl[i].split('=')[0]) {
case 'bgc':
document.body.style.background = bl[i].split('=')[1];
break;
case 'wd':
div.style.width = bl[i].split('=')[1] + 'px';
break;
default:
null;
break;
}
}
}
</script>
用 location.hash 取出錨點、切掉井號、以 ? 拆成多組,再以 = 分出鍵值,逐一套用即可。
這段手刻的解析邏輯其實可以用標準 API 取代,程式碼更短也更不容易出錯:
var q = new URLSearchParams(location.hash.slice(1));
document.body.style.background = '#' + q.get('bgc');
div.style.width = q.get('wd') + 'px';
第二題的方向是從 b 抓資料回 a,這裡用的算是障眼法。
做法是在 a 頁面動態建立一個 iframe,把 src 指向 b 頁面,並設 display: none 讓它隱形。等載入完成後,透過 contentDocument 取得該文件內容,再從裡頭抓出需要的元素搬到 a 上。
<span>11111111111</span>
<script>
var fram = document.createElement('iframe');
fram.src = 'https://www.vip.com/kongzhi/fram2.html';
fram.style.display = 'none';
document.body.appendChild(fram);
fram.onload = function(){
var doc = fram.contentDocument || fram.contentWindow.document;
var p = doc.querySelector('p');
document.body.appendChild(p);
}
</script>
幾個實作上要留意的地方:
contentDocument || contentWindow.document 的雙寫是為了相容舊版 IE,現代瀏覽器只需要前者;postMessage;