janpaul123 / delayed-scroll-restoration-polyfill

Polyfill that mimics Chrome's scroll restoration behavior.
Other
105 stars 8 forks source link

history.pushState not being called #8

Open subatomicglue opened 5 years ago

subatomicglue commented 5 years ago

When clicking my <a href="">s, pushState is not being called automatically. (I added console logs to pushState, so I could watch when it's called...)

When I register the following code (below), which intercepts all <a href="">s and calls pushState, then pushState is (of course) called, and scroll is restored on browser back button.

function clickHandler(e) {
  var e = window.e || e;

  if (e.target.tagName !== 'A')
      return;

  window.history.pushState( {}, e.target.textContent, e.target.href);

  // trigger our router through the hashchange event, or the page wont update
  window.dispatchEvent(new Event('hashchange'));
}

if (document.addEventListener)
    document.addEventListener('click', clickHandler, false);
else
    document.attachEvent('onclick', clickHandler);

Without calling pushState manually like I do above, there never seems to be a state other than null in onPopState, so I never get scrolls restored...

Is that expected? I didn't see mention that we had to call pushState to get this to work.

(Using webpack with a custom router based on http://joakim.beng.se/blog/posts/a-javascript-router-in-20-lines.html)