[英]Prevent Adding To History API Array
如果用戶在特定/同一頁面上並且只有 location.search 參數更改,是否可以阻止將當前頁面 URL 添加到歷史記錄? 該頁面使用新的搜索參數重新加載,但如果路徑名沒有更改,我無法阻止 URL 存儲到 History 數組中。
當我單擊后退按鈕時,我需要在歷史記錄中只有一個產品頁面,而不是根據 location.search 更改的次數來顯示“數字”。 我正在嘗試這個,但它不起作用,我做錯了什么?
// Note: Page Reloads when changing the search parameters ( window.location.search params can change but the URL should not be added to History API)
if(document.querySelector('.prod-page')) { // check if user is on Prod Page
console.log("user is on PDP PAGE");
const prodPage = window.location.pathname; // get Prod Page Location Pathname
window.addEventListener('popstate', (e) => { // on browser "Back" click
e.preventDefault();
if(prodPage) { // if user is still on Product Page
window.history.pushState(null, null, null); // Prevent adding current URL (another product page url) to History API
}
});
}
我相信正在發生的事情是當事件偵聽器被稱為prodPage
時超出范圍。 您可以嘗試將prodPage
傳遞給回調,以便它可以訪問它,如下所示:
window.addEventListener('popstate', (e, prodPage) => { // on browser "Back" click
e.preventDefault();
if(prodPage) { // if user is still on Product Page
window.history.pushState(null, null, null); // Prevent adding current URL (another product page url) to History API
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.