visionmedia / page.js

Micro client-side router inspired by the Express router
http://visionmedia.github.com/page.js
7.67k stars 687 forks source link

history.state is cleared on initial page load #610

Open AshfordN opened 1 year ago

AshfordN commented 1 year ago

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

https://github.com/visionmedia/page.js/blob/4f9991658f9b9e3de9b6059bade93693af24d6bd/index.js#L168

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.