2

I am using a window.onhashchange event handler to listen for hash change events. It works when I hit the back button, forward button, or enter another hash url in the address bar. However, it does not work when I click on DOM elements that initiate routing. E.g. I click on my homepage logo and go from localhost:3000/#place to localhost:3000/#.

I have not found an answer to this but have seen other people indicating this is not possible, such as the SO post found here. Is there a way to detect any hash change event, regardless of what initiates the hash change?

Community
  • 1
  • 1
skwny
  • 2,930
  • 4
  • 25
  • 45
  • Doesn't your router, react, backbone, etc, supply this feature? – Robert Moskal Dec 21 '16 at 02:11
  • @RobertMoskal Yes, it does. However, I only need to detect this event for a very specific purpose (to turn off a video conferencing stream that lingers when changing URLs on an SPA), and would rather not have to setup a flag in my routes to detect this. This flag would need to attach to every route and would feel a bit 'hackish'. – skwny Dec 21 '16 at 02:22
  • When you say that `window.onhashchage` isn't working are you sure the page isn't being reloaded? I have just done a simple test with `window.onhashchange = function() {console.log(this.location.hash);}` clicking on DOM elements and it seems to log the hash every time. – NewToJS Dec 21 '16 at 02:38
  • @NewToJS What specifically do you mean by 'page isn't being reloaded`? I am using a SPA so the hash part of the URL changes, but beyond that it is not a reload, as far as I can tell. – skwny Dec 21 '16 at 03:09
  • So you don't have anything in your browser console? no logs? no errors? Can you give an example of what you have tried? – NewToJS Dec 21 '16 at 03:13
  • @NewToJS No, no errors or logs. I set an alert within the callback which does in fact execute whenever I hit back and forward buttons, and when I enter something into the address bar. But clicking on a button that engages the router to go to another URL does not invoke the callback. – skwny Dec 21 '16 at 04:11

0 Answers0