Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if the user arrived to the current page via the browser back button

I have a site where if a user navigates to a certain page then he gets a dialog notification depending on some condition on the page. The user can navigate to other pages from this page and of course can press the back button on those pages to navigate back to this page.

I'd like to detect if the user arrives via the back button to this page, so the dialog notification is not shown again (because the user has already seen it).

Is there a way to detect this reliably?

like image 989
Tom Avatar asked Oct 31 '22 09:10

Tom


2 Answers

MDN list of window events

Your best possibility may be window.onpageshow = function(){};

An event handler property for pageshow events on the window.

window.onpageshow = function(event) {
    if (event.persisted) {
        alert("From back / forward cache.");
    }
};
like image 70
kemicofa ghost Avatar answered Nov 09 '22 07:11

kemicofa ghost


Input trick is not longer working. Here's the solution I use:

if (window.performance && window.performance.navigation.type === window.performance.navigation.TYPE_BACK_FORWARD) {
    alert('Got here using the browser "Back" or "Forward" button.');
}
like image 21
David TG Avatar answered Nov 09 '22 05:11

David TG