quirkey / sammy

Sammy is a tiny javascript framework built on top of jQuery, It's RESTful Evented Javascript.
http://sammyjs.org
MIT License
2.99k stars 384 forks source link

Issues with the back button, IE11 and setLocation #226

Open lkinsella opened 9 years ago

lkinsella commented 9 years ago

There may be an issue with setting the location. Either that or I'm doing something wrong. I originally ran into problems with IE11 and the back button not appearing to work properly.

I added some logging to the setLocation function like this:

    // set the current location to `new_location`
    setLocation: function(new_location) {
      if (/^([^#\/]|$)/.test(new_location)) { // non-prefixed url
        if (_has_history && !this.app.disable_push_state) {
          new_location = '/' + new_location;
        } else {
          new_location = '#!/' + new_location;
        }
      }

      console.log('_has_history = ',_has_history);
      console.log('app.disable_push_state = ',this.app.disable_push_state);
      console.log('regex test = ',/^\//.test(new_location));
      console.log('old location = ',this.getLocation());
      console.log('new location = ',new_location);

      if (new_location != this.getLocation()) {
        // HTML5 History exists and new_location is a full path
        if (_has_history && !this.app.disable_push_state && /^\//.test(new_location)) {
          history.pushState({ path: new_location }, window.title, new_location);

            console.log('pushed state');

          this.app.trigger('location-changed');
        } else {
           console.log('setting location');

          return (window.location = new_location);
        }
      }
    },

Now with the above code I see the following:

Firefox - http://screencast.com/t/hYNSuiJ5 IE11 - http://screencast.com/t/94h8qkEAYT

Under Firefox the old and new url are both correct and start with /search#/. But under IE11 the new url starts with #/. This means the latter never fulfills the regex and so never updates the history (breaking back?).

I can fix it by doing the following:

        var location = this.getLocation();
        var match = /^(.*?)#\//.exec(location);

        if (/^#.*/.test(new_location)) new_location = new_location.replace('#',match[1] + '#');

Basically pulling out the content before the # in the old url and stuffing it infront of the # in the new url if the url begins with a #. But of course I don't know if this has any knock-on effects elsewhere in Sammy.

If I do this it then works as expected in Firefox and IE11. Yay!

I'm not sure why it would be missing some of the url but it's definately causing the issues we are seeing.