1

So when it comes to url changes everyone on Stackoverflow seems to suggest using 'onhashchange', but no one even speaks about the fact that this event is - like it name says - only triggered if you use hashes. And I don't want to use random hashes in my URL.

So I am looking for a way to watch window.location.pathname to detect any change there. But Vue seems to only be able to watch its own properties. So how do I do this? Thank you!

Hillcow
  • 890
  • 3
  • 19
  • 48
  • You should us `vue-router` for a Single-Page-Application with multiple sites. Each component gets it's own route which can be used to watch other properties. BTW: What are you trying to achieve anyways? – Bennett Dams Jul 06 '18 at 14:58
  • I don't have a single page application, it is just one case. I am building a feature that the reddit redesign is using: when clicking on a post I am opening a lightbox rather the a new page. Now when the back button is triggered I need to detect that to remove the lightbox. – Hillcow Jul 06 '18 at 15:01
  • Possible help here: https://stackoverflow.com/questions/32148423/how-to-use-or-is-it-possible-mutationobserver-to-monitor-window-location-pathn – Chad Moore Jul 06 '18 at 15:11
  • 1
    @Hillcow In this case this has nothing to do with Vue. Check `window.onpopstate` https://developer.mozilla.org/de/docs/Web/API/WindowEventHandlers/onpopstate – Bennett Dams Jul 06 '18 at 15:18

1 Answers1

2

Could try this: (should work only on history mode, will not work on hash mode)

mouted () {
    window.addEventListener(
         'popstate', this.handleHistoryChange
         ) 
},

destroyed () {
     window.removeEventListener(
            'popstate', this.handleHistoryChange
        ) 
   }
Yaniv Peretz
  • 1,118
  • 2
  • 13
  • 22
  • it really only works for going back or forward in the browser history. If it was triggered somehow by a SPA it wont work. – Rafael Costa Jul 13 '23 at 18:35