點擊 `詳情` 時,需先異步上報統計接口 `https://10.108.23.198/...`,再跳轉目標頁。
| 方案 | 優點 | 缺點 | 適用場景 |
|---|---|---|---|
| 1. `navigator.sendBeacon`(推薦) | 頁面卸載前也能可靠發送、無需阻塞跳轉、瀏覽器原生支持 | 僅支持 POST、無法攔截響應 | 埋點、日誌上報、無需依賴響應 |
| 2. `onclick` 阻止默認 + `fetch`/`XMLHttpRequest` + `location.href` | 可處理響應、支持 GET/POST、邏輯可控 | 需手動阻止跳轉、異步回調中跳轉、用戶感知延遲 | 需根據統計接口響應決定是否跳轉 |
| 3. `target="_blank"` + `onclick` 發圖片請求 | 極簡、不阻塞主頁 | 新窗口體驗差、圖片請求大小限制、不可靠 | 極簡統計、不介意新窗口 |
<a href="lstjxqgd.jsp" onclick="reportAndGo(this, event)">詳情</a>
<script>
function reportAndGo(link, e) {
e.preventDefault(); // 阻止默認跳轉
const url = 'https://10.108.23.198/stat'; // 統計接口
const data = JSON.stringify({ from: link.href, time: Date.now() });
// sendBeacon 返回 true 表示瀏覽器已排入發送隊列
if (navigator.sendBeacon(url, data)) {
// 立即跳轉,無需等待發送完成
location.href = link.href;
} else {
// 降級:圖片請求
new Image().src = url + '?' + new URLSearchParams({ from: link.href });
location.href = link.href;
}
}
</script>
async function reportAndGo(link, e) {
e.preventDefault();
try {
const resp = await fetch('https://10.108.23.198/stat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ from: link.href }),
keepalive: true // 頁面卸載前也嘗試發送
});
if (resp.ok) location.href = link.href;
else alert('統計上報失敗,仍將跳轉'), location.href = link.href;
} catch (err) {
console.error(err);
location.href = link.href; // 容錯:統計失敗不阻斷業務
}
}
優先使用 `navigator.sendBeacon`,簡單可靠不阻塞跳轉。