pageshow's event listener on a React component not working properly

3.9k Views Asked by At

I have the following scenario where I need to run some "code" when entering a page for the first time or returning to it from another page.

Safari's cache feature (https://webkit.org/blog/516/webkit-page-cache-ii-the-unload-event/) is causing that, since it is caching my page and not executing anything.

I followed their recommendation of adding an event listener to 'pageshow' event, this way I can check if that event is persisted and then run what I need.

This example is basically what I'd like to have:

  • first page access... attach the listener = Cool, I have that.
  • if I navigate out of the page and get back (using Safari) it will fire my listener on pageshow = Cool, I have that... almost.
  • the listener should be fired every time that I navigate back to that page = Not cool, my listener fires once.

I'm using react and componentDidMount() is where I'm preparing everything:

enter image description here

It works for the first time.. I'm able to navigate out of my page and get back to it + executing what I need.

The problem is: repeating the "navigate out of my page and get back" a second time won't do anything.. looks like the listener gets deleted or something.

1

There are 1 best solutions below

2
On BEST ANSWER

After two days trying to find a way... my coworker asked me to try a listener on 'popstate'. I was so into trying to get the 'pageshow' listener to work that I completely forgot to test that one; it worked flawlessly:

window.addEventListener('popstate', function(event) {