兩個純 HTML 頁面之間要交換資料,後端不介入的前提下該怎麼做?把問題拆成兩個方向來看會清楚很多。
假設有 a.html 與 b.html:
以下討論都建立在同源的前提上。
利用 HTML 錨點(hash)不會觸發重新請求的特性,把參數塞進 URL。
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>
跳轉後網址尾部帶著一串參數,但並不影響頁面本身載入。
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:
break;
}
}
}
</script>
b 頁把 hash 去掉井號、以問號切開,再一組組比對 key 並套用樣式,參數就成功過來了。
這個技巧有點像障眼法:a 頁動態插一個 display:none 的 iframe,src 指向 b 頁,等 onload 後透過 contentDocument 取得 b 頁的文件物件,再從裡面挑出需要的元素搬到 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>
iframe 這招的限制很明確:跨域時同源政策會直接擋住 contentDocument 的存取,所以只適合同一個站台內部的頁面。而且它會真的發一次請求、載入整份文件,只為了拿幾個值其實相當耗資源。
如果目的只是傳值,hash 或 query string 才是首選;若資料量較大或需要讀寫,localStorage 搭配 storage 事件會是更乾淨的方案——a 頁寫入、b 頁監聽事件就能即時收到通知,不必輪詢也不必繞路。