1

I use to listen to hashchange handler event. But now with HTML5 you can change the url without using the hash. How can add a listener to url changes?

0

1 Answer 1

1

hash-changes can happen even without the use of JS. Like the default behaviour of clicking an anchor link can trigger a hash-change.

The HTML5 history object can only be manipulated through JS. For this there is pushState() and replaceState(). Once used, the browser back and forward buttun will trigger the popstate event. There are no other event handlers that I know of for HTML5 History.

$(window).bind("popstate", function() {
    console.log(window.location.href);
});

If you require a trigger whenever something is pushing states to the history object, then you should rely on the whoever is calling this to allow observers (callbacks) for it.

Otherwise you could try something something not so robust:

function onPushState(callback) {
    (function(pushState) {
       history.pushState = function() {
           pushState.apply(this, arguments);
           callback.apply(window, arguments);
       };
    })(history.pushState);
}

onPushState(function() {
    console.log(window.location.href);
});

http://jsfiddle.net/Cxjey

You could do the same of replace state.

Again, this might not be a good idea as you are changing default browser behaviour.

1
  • I've made some edit, perhaps it will give you some more insight into it. May 10, 2012 at 21:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.