類似「歷史觀看」「最近瀏覽」功能,需在客戶端記錄用戶點擊的鏈接(標題+URL),並在側邊欄或頁面底部展示最近 5-10 條記錄,刷新頁面不丟失。
| 方案 | 優點 | 缺點 |
|---|---|---|
| Cookie | 無需服務端存儲、跨頁面持久、實現簡單 | 容量限制 4KB、隨請求發送增加流量、同域共享 |
| localStorage | 5MB 容量、不隨請求發送、API 友好 | IE8+ 支持、同源策略限制 |
| Session + 數據庫 | 跨設備同步、可統計分析、無容量壓力 | 需登錄、增加服務端負載、實現複雜 |
<script>
// 記錄點擊
document.addEventListener('click', function(e) {
let a = e.target.closest('a');
if (!a || !a.href) return;
let title = a.innerText.trim();
let url = a.href;
if (!title || title.length > 50) return; // 過濾無效
saveHistory(title, url);
}, true);
// 存入 Cookie(最多 10 條,30 天有效)
function saveHistory(title, url) {
let key = 'browse_history';
let list = JSON.parse(getCookie(key) || '[]');
// 去重
list = list.filter(item => item.url !== url);
// 新增到頭部
list.unshift({title, url, time: Date.now()});
// 截取前 10
list = list.slice(0, 10);
setCookie(key, JSON.stringify(list), 30);
}
// 顯示歷史
function renderHistory(containerId) {
let list = JSON.parse(getCookie('browse_history') || '[]');
let html = list.map(item =>
`${item.title}`
).join('
');
document.getElementById(containerId).innerHTML = html || '暫無瀏覽記錄';
}
// Cookie 工具函數
function setCookie(name, value, days) {
let exp = new Date();
exp.setTime(exp.getTime() + days*24*60*60*1000);
document.cookie = `${name}=${encodeURIComponent(value)};expires=${exp.toGMTString()};path=/`;
}
function getCookie(name) {
let arr = document.cookie.match(new RegExp('(^| )' + name + '=([^;]*)(;|$)'));
return arr ? decodeURIComponent(arr[2]) : null;
}
// 頁面加載時渲染
window.addEventListener('DOMContentLoaded', () => renderHistory('history-box'));
</script>
// 頁面放置顯示容器
<div id="history-box"></div>
JSON 序列化存儲結構化數據,避免手動拼接分隔符出錯。document,動態生成的鏈接也能捕獲。localStorage 作為備選,突破容量限制。