0

How would I put a dynamic page created with Ajax to the smootState.js history. I've tried using history.pushState() but that didn't seem to work. For example, with an anchor you land on a page named Projects.html. From that page on you do an ajax call and insert new content into a div and use history.pushState() to change the url to Projects.html?id=1. This page is also fully recreated if you do a refresh, but if you navigate somewhere else and trying coming back to this page it throws an Uncaught TypeError: Cannot read property 'href' of undefined.

This is the part from the smoothState.js plugin to where I am trying to "plug-in".

 /** Handles the popstate event, like when the user hits 'back' */
    onPopState = function ( e ) {
      if(e.state !== null) {
        var url = window.location.href,
          $page = $('#' + e.state.id),
          page = $page.data('smoothState'),
          diffUrl = (page.href !== url && !utility.isHash(url, page.href)),
          diffState = (e.state !== page.cache[page.href].state);

        if(diffUrl || diffState) {
          if (diffState) {
            page.clear(page.href);
          }
          page.load(url, false);
        }
      }
    },

and this is how it stores the history object.

var destUrl = cache[settings.url].destUrl;

/** Prepare a history entry */
state = options.alterChangeState({ id: elementId }, cache[settings.url].title, destUrl);

/** Update the cache to include the history entry for future comparisons */
cache[settings.url].state = state;

/** Add history entry */
window.history.pushState(state, cache[settings.url].title, destUrl);

Is there a better way to handle this?

Svedr
  • 589
  • 2
  • 6
  • 21
  • [history.js](https://github.com/browserstate/history.js/) tried with this? its simpler – Luminous_Dev Feb 22 '17 at 05:24
  • @Luminous_Dev Why? Could you please elaborate a little. What can I do with history.js that can't be done with the native History API and what would it help with this example? – Svedr Feb 22 '17 at 06:28
  • history.js first of all supports most of the browsers, less code to write. And I think, you need to add the content data on the state when you push and rebind the view with that data you stored within that state when you come back to it – Luminous_Dev Feb 22 '17 at 06:53
  • Hi there, I'm doing exactly the same thing, did you ever find a solution? Cheers – Popmatik Feb 28 '18 at 10:04

0 Answers0