場景:禁止瀏覽器點擊返回鍵做后退,以及鼠標or觸摸板做后退的情況。
大多數網上提供的解決方案都是 👇 但這不適用於單頁面應用程序
history.pushState(null, null, document.URL); window.addEventListener('popstate', function () { history.pushState(null, null, document.URL); });
實現:路由監聽,導航結束的時候調用window.history.pushState方法,僅改變網址,網頁不會跳轉,也不會獲取到新的內容,本質上網頁還停留在原頁面從而實現禁止返回鍵。
this.router.events.subscribe((event: any) => { if (event instanceof NavigationEnd) { history.pushState(null, null, document.URL); } });
此隨筆乃本人學習工作記錄,如有疑問歡迎在下面評論,轉載請標明出處。
如果對您有幫助請動動鼠標右下方給我來個贊,您的支持是我最大的動力
