Disable brower's auto scroll after a page refr

2019-01-18 05:19发布

问题:

Is there a way to disable the behavior where some modern browsers (Chrome and Safari) remember your scroll position on a page refresh?

回答1:

For browsers that support history.scrollRestoration, the auto scroll behavior can be turned off:

if ('scrollRestoration' in history) {
  history.scrollRestoration = 'manual';
}

source: https://developers.google.com/web/updates/2015/09/history-api-scroll-restoration



回答2:

Have you tried firing this after document is ready?

$(document).ready(function(){
    window.scrollTo(0, 0);
});

if that does not work...

$(document).ready(function(){
    setTimeout(function(){
        window.scrollTo(0, 0);
    }, 1);
});

Which will push this to the bottom of the call stack



回答3:

not just for chrome,but for all i think this will work well.

window.onload = function () {
    window.scrollTo(0, 0);
};

After update of your question:

I think its better if we use some cookies or session storage.



回答4:

Instead of hoping a setTimout ends up at the bottom of the stack - I rather enforce it that we hit the scroll position we want. I still consider this a hack, I was hoping for some kind of browser event we bind to.

var scrollToYPos = 100;
var interval = setInterval(checkPos, 0);

function checkPos() {
    if ($(window).scrollTop() == scrollToYPos) {
        clearInterval(interval);
    } else {
        window.scrollTo( 0, scrollToYPos );
        checkPos();               
    }
}      


回答5:

I encountered this same issue. Here's the basic solution I came up with:

      // scroll the user to the comments section if we need to
      wt = win.scrollTop();
      wb = wt + win.height();
      // if scroll position is 0, do this (it's a fresh user), otherwise
      // the browser is likely to resume the user's scroll position, in 
      // which case we don't want to do this
      yab.loaded().done(function() {
        // it seems that browsers (consistently) set the scroll position after
        // page load.  Accordingly wait a 1/4 second (I haven't tested this to the lowest
        // possible timeout) before triggering our logic
        setTimeout(function() {
          // if the window top is 0, scroll the user, otherwise the browser restored
          // the users scroll position (I realize this fails if the users scroll position was 0)
          if(wt === 0) {
            p = self.container.offset().top;
            if(wb != p) {
              win.scrollTop(p - th - 20);         
            }
          }              
        }, 250);
      });


回答6:

I think the easiest way would be to trick the browser into a reload that it thinks is a new page.

window.location = window.location

All the browsers I've tested this in it works consistently. I would personally stay away from onload callbacks as they can cause jumps during load that aren't too visually appealing.