visionmedia / page.js

Micro client-side router inspired by the Express router

Home Page:http://visionmedia.github.com/page.js

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

history.state is cleared on initial page load

AshfordN opened this issue · comments

When page.js is started, it clears the history.state via the following line.

this.replace(url, null, true, opts.dispatch);

This is actually problematic for apps that need to access history.state, especially when navigating through the browser's history. The problem is only present on the first load of the page, since that's the only time page.js automatically interacts with the history state. Indirect interaction through ctx.save() from within a route handler isn't really an issue since that would be intentional — and therefore, avoidable.
One way of mitigating this problem is to allow page.start() to accept an initial state. That way, if an app needs to retain the history state, history.state can be passed in as the initial state. The new page.start() function would look something like the following:

Page.prototype.start = function(options, initialState=null) {
  var opts = options || {};
  this.configure(opts);

  if (false === opts.dispatch) return;
  this._running = true;

  var url;
  if(isLocation) {
    var window = this._window;
    var loc = window.location;

    if(this._hashbang && ~loc.hash.indexOf('#!')) {
      url = loc.hash.substr(2) + loc.search;
    } else if (this._hashbang) {
      url = loc.search + loc.hash;
    } else {
      url = loc.pathname + loc.search + loc.hash;
    }
  }

  this.replace(url, initialState, true, opts.dispatch);
};

Which would allow you to do something like this:

// --snip--
page.start(opts, history.state);

I decided to open this issue, as a RFC, rather than submitted a PR, because I'd like some feedback on my proposal.