How to detect user if they visited the webpage by press back button

516 Views Asked by At

Let say, visitor visited my website example.com and then visited other website (maybe by clicking any link of my webpage or maybe manually typing to address bar) in same tab and then he pressed browser back button and came back to my website example.com

How can i detect that the user visited my site again with back button?.

I am trying

With Popstate :

window.addEventListener('popstate', function(event) {
  if (event.state && event.state.source === 'example.com') {
    console.log('User returned to example.com by clicking the back button');
  }
});

With onpopstate

window.onpopstate = function(event) {
  if (event && event.state) {
    console.log('User returned to example.com by clicking the back button');
  }
};

With pageshow

window.addEventListener('pageshow', function(event) {
  if (event.persisted) {
    console.log('User returned to example.com by clicking the back button');
  }
});

Sadly, none of these worked!!

1

There are 1 best solutions below

1
Rajeev On BEST ANSWER

You can achieve desire output using window.performance

<script>
if (window.performance && window.performance.navigation.type === 2) {
  console.log('User returned to example.com by clicking the back button');
}
</script>