I want to execute a js function when users click on back/forward button after redirect. I have a half working function below:
detectHistoryEvent();
function detectHistoryEvent() {
console.log(performance.navigation.type); // deprecated
console.log(performance.getEntriesByType("navigation")[0].type); // currently used
if (performance.getEntriesByType("navigation")[0].type && performance.getEntriesByType("navigation")[0].type === 'back_forward') {
themethod(); // method I want to run
}
}
Working Scenario 1:
PAGE 1
user clicks delete button that executes POST REQUEST
.PAGE 2
.PAGE 2
when user clicks on back button, it will redirect to PAGE 1
. After redirection, it will execute themethod()
because of the function above. This is because the value of navigation is back_forward
.Not Working Scenario 2:
PAGE 1
user clicks href that executes GET REQUEST
.PAGE 2
.PAGE 2
when user clicks on back button, it will redirect to PAGE 1
. However the themethod()
is not executed. This is because the value of nagivation is navigate
just like a normal href click.Is it possible to check if user clicks on back/forward button even if PAGE 1
executes GET REQUEST
?
After days of searching, removed the method on my question and use the solution using the code below instead:
window.onpageshow = function(event) {
if (event.persisted) {
themethod();
}
};