5

I know that in modern browsers I can change the URL silently (without page reload) like this:

window.history.pushState(“object or string”, “Title”, “/new-url”);

But I want to be able to detect changes in URL. When user enters the new URL in the address bar how can I handle the event and prevent the page from reloading?

P.S. I know I can use onhashchange but I just don't want to use hashes :)

4
  • I'd have a look at the source code of Backbone.js (Backbone.Router) or AngularJS. Commented Dec 14, 2013 at 17:49
  • 2
    It seems pretty hostile to prevent a user from entering an address in the address bar. And (thankfully, for us users), it's not possible. Commented Dec 14, 2013 at 17:56
  • @hgoebl thanks, I look forward to your answer. Commented Dec 15, 2013 at 5:57
  • @StephenThomas User wants to view the entered URL and I will show him/her but just without reloading the page. I don't think handling the URL of my own domain would be hostile. Of course I don't expect that changing the URL to another domain would be reported to me! Commented Dec 15, 2013 at 6:01

1 Answer 1

2

As stated in Event when window.location.href changes it is not possible without polling. This was 2010. Maybe in the meanwhile there is a solution for HTML5 browsers.

Probably you already know that not using hashchange has drawbacks regarding server-side, crawling, 404-detection, ...

But using hashes has disadvantages as well, especially when it comes to deep links sent by mail (redirects don't transport hashes, typically used by webmail-clients to have clean referers).

I recommend to use a tested library for url-routing and history API. I'm sure you find one either at microjs.com, JSter or JSDB.IO. There are many which do a graceful fallback on disabled browsers like MSIE.

My best bets would be history.js and Crossroads.js (with Hasher).

If you already use a MVC framework like Backbone.js, AngularJS, Ember or the like you'll get what you want for free.

After all I'm not really sure whether any of these libraries are able to supress reloading of the (single-) page when location.href changes. Since your losing most of your state I'd use #hashes. IMHO, Users of Single-Page-Apps shouldn't change the browser location but use navigation options of your App.

Sign up to request clarification or add additional context in comments.

1 Comment

1) polling is not pretty at all, but i think it might work! 2) Thanks about the links, I will take a look at those libraries. 3) I agree with you that users of a single-page-app shouldn't change the browser location manually, but the question is what should i do if that happens?!

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.