I have the following conditions for popstate, but the problem is that popstate doesn’t fire when the back button is clicked. This is the code for Shopify. Maybe someone has ideas on how to fix my code so that it works, or you can replace popstate with another event.
window.addEventListener('load', function() {
if (!window.history.state) {
history.replaceState({ page: document.URL }, null, document.URL);
}
// let popstateTriggered = false;
// let popstateTimeout = setTimeout(function() {
// if (!popstateTriggered) {
// let previousCollectionData = JSON.parse(localStorage.getItem('collectionData')) || [];
// if (previousCollectionData.length > 2) {
// previousCollectionData = previousCollectionData.slice(0, 2);
// }
// localStorage.setItem('collectionData', JSON.stringify(previousCollectionData));
// }
// }, 0);
window.addEventListener('popstate', function(event) {
let previousCollectionData = JSON.parse(localStorage.getItem('collectionData')) || [];
console.log('welllllll' + event)
previousCollectionData = previousCollectionData.slice(0, -1);
localStorage.setItem('collectionData', JSON.stringify(previousCollectionData));
if (previousCollectionData.length > 0) {
window.location.href = previousCollectionData[previousCollectionData.length - 1].url;
} else {
window.location.href = "/";
}
});
});
P.S The event is triggered if I click on any random place on the page I want to leave. maybe there is an opportunity to somehow generate some kind of action that the page itself performs and launches popstate