Search code examples
javascriptbrowser-history

Detect non-programmatic url hash changes


I'm using window.onhashchange to detect browser hash changes. But is there a way to only trigger the callback if the hash was changed in a non-programmatic way?

I am not asking how to use onhashchange. I am trying to avoid triggering it when I set the hash programmatically.

Basically, I want to do something similar to:

window.onhashchange = () => { /* ... */ };

But I don't want the callback to trigger if the code did the following:

window.location.hash = 'hello-world';    

Thanks!


Solution

  • I ended up solving it by simply setting a flag, which seems like a hack, but given JavaScript execution environments are single-threaded, should work fine.