需求:防止用戶在短時間內連續刷新頁面(5秒內),但允許已授權頁面(B頁)正常跳轉不觸發攔截。
(function() {
const loadTime = Date.now();
let hasAuth = false; // 授權標記
window.addEventListener('beforeunload', function(e) {
// 無授權時直接放行(如直接訪問 B 頁)
if (!hasAuth) return;
const elapsed = Date.now() - loadTime;
if (elapsed < 5000) {
e.preventDefault();
e.returnValue = ''; // 觸發瀏覽器原生確認對話框
}
});
// 暴露授權設置供 B 頁調用
window.__grantAuth = function() { hasAuth = true; };
})();
// 用戶點擊「去 B 頁」按鈕時
function goToB() {
const win = window.open('B.html', '_blank');
// 等待 B 頁加載完成後授權(跨域需 postMessage)
win.onload = () => win.__grantAuth?.();
}
<script>
// 頁面加載即聲明已授權(同域直接調用)
window.opener?.__grantAuth?.();
// 或跨域通信
window.addEventListener('message', e => {
if (e.data === 'grant-auth') window.opener?.postMessage('auth-ok', '*');
});
</script>
// Vue Router / React Router 導航守衛
router.beforeEach((to, from, next) => {
if (to.meta.needAuth && !store.state.auth) {
next('/login?redirect=' + to.fullPath);
} else {
next();
}
});
// 刷新攔截獨立於路由守衛,僅處理瀏覽器原生刷新/關閉
window.addEventListener('beforeunload', e => {
if (store.state.unsavedChanges) {
e.returnValue = '有未保存內容,確定離開?';
}
});