change url without redirecting using javascript

118,425

Solution 1

use pushState:

window.history.pushState("", "", '/newpage');

Solution 2

If you want to know exactly what they using, it's Backbone.js (see lines 4574 and 4981). It's all mixed up in there with the jQuery source, but these are the relevant lines of the annotated Backbone.Router source documentation page:

The support checks:

  this._wantsPushState = !!this.options.pushState;
  this._hasPushState = !!(this.options.pushState && window.history && window.history.pushState);

The route function:

route: function(route, name, callback) {
    Backbone.history || (Backbone.history = new History);

    if (!_.isRegExp(route)) route = this._routeToRegExp(route);

    if (!callback) callback = this[name];

    Backbone.history.route(route, _.bind(function(fragment) {
        var args = this._extractParameters(route, fragment);

        callback && callback.apply(this, args);

        this.trigger.apply(this, ['route:' + name].concat(args));

        Backbone.history.trigger('route', this, name, args);
    }, this));

    return this;
},

Choosing between hash and push states:

// Depending on whether we're using pushState or hashes, and whether
// 'onhashchange' is supported, determine how we check the URL state.
if (this._hasPushState) {
    Backbone.$(window).bind('popstate', this.checkUrl);
} else if (this._wantsHashChange && ('onhashchange' in window) && !oldIE) {
    Backbone.$(window).bind('hashchange', this.checkUrl);
} else if (this._wantsHashChange) {
    this._checkUrlInterval = setInterval(this.checkUrl, this.interval);
}​

More on what they're up to:

// If we've started off with a route from a `pushState`-enabled browser,
// but we're currently in a browser that doesn't support it...
if (this._wantsHashChange && this._wantsPushState && !this._hasPushState && !atRoot) {
    this.fragment = this.getFragment(null, true);
    this.location.replace(this.root + this.location.search + '#' + this.fragment);

    // Return immediately as browser will do redirect to new url
    return true;

    // Or if we've started out with a hash-based route, but we're currently
    // in a browser where it could be `pushState`-based instead...
} else if (this._wantsPushState && this._hasPushState && atRoot && loc.hash) {
    this.fragment = this.getHash().replace(routeStripper, '');
    this.history.replaceState({}, document.title, this.root + this.fragment);
}

if (!this.options.silent) return this.loadUrl();

And the coup 'd grace:

// If pushState is available, we use it to set the fragment as a real URL.
if (this._hasPushState) {
     this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url);
}

You should read the annotated Backbone.js link I provided at the top. Very informative.

Share:
118,425

Related videos on Youtube

kb858
Author by

kb858

A software Engineer with great passion for learning new and interesting things

Updated on September 17, 2020

Comments

  • kb858
    kb858 over 3 years

    I would like to know how to change the url without redirecting like on this website http://dekho.com.pk/ads-in-lahore when we click on tabs the url changes but the page dosent reload completely. There are other questions on stackoverflow indicating that it is not possible but i would like to know how the above mentioned website have implemented it. Thanks

    • Sushant Gupta
      Sushant Gupta over 11 years
      On the link you mentioned, same webservice is called but with different parameters.
    • Jared Farrish
      Jared Farrish over 11 years
      history.pushState(). There's also jQuery in there, but that particular technique has got to be. push state with a fall back for older browsers.
    • GG.
      GG. over 11 years
      You can also use window.location.hash and modify url.com/page#hash.
    • Jared Farrish
      Jared Farrish over 11 years
      History.js seems to be a fairly comprehensive take on the pushState technique. See the demos.
  • kb858
    kb858 over 11 years
    Thank you for your answer.it was very informative. i dont know backbone yet so i am going for the pushstate as it fulfills all my needs.
  • Jared Farrish
    Jared Farrish over 11 years
    Backbone.js is built around it's router, as it's a "single page app". Although you may not be experienced enough yet to see it in my answer above, that's exactly what Backbone.js is doing, as well has graceful degradation (for those who don't have browsers that support it). See my link in comment under your question; I'd use a library like github.com/balupton/History.js, not roll your own. Unless you know what you're doing.
  • kb858
    kb858 over 11 years
    I am using History.js as i am a newb :)
  • Prathamesh Rasam
    Prathamesh Rasam almost 9 years
    refer link for more details diveintohtml5.info/history.html
  • Martin Schneider
    Martin Schneider over 7 years
  • Pierre
    Pierre about 6 years
    window.history.replaceState(data, title, url); is also useful
  • Dexter Bengil
    Dexter Bengil over 5 years
    wow, this works like a charm!
  • okram
    okram about 5 years
    doesnt work in firefox - "SecurityError: The operation is insecure."
  • VoidZA
    VoidZA over 2 years
    @Pierre thanks, window.history.replaceState(data, title, url); is especially useful if you do not want to mess with the actual history, so when the user clicks back they go to the previous page, not the previous url you pushed.