3

It looks like Vuejs is automatically scrolling to the top of a page when you push the back button, which is weird because by default the window doesnt even scroll to the top when you change route in a SPA or go to a new page. You need to explicitly set scrollBehaviour to scroll to the top. So how can we prevent the page automatically scrolling to the top when you press the back button.

beforeRouteLeave (to, from, next) { alert('Are you sure you want to leave this page and lose unsaved changes') // Notice how the page automatically scrolls to the top here even if the user were to response 'No' in a dialog situation } 

Heres a code pen of the problem https://codepen.io/anon/pen/bOGqVP

4
  • You can return a promise that resolves to some coordinates object instead of an object itself. Does that help you? Commented Dec 9, 2018 at 11:50
  • Could you give me a link to this solution kind sir!? I have found somewhat similar approaches but they arent working. Upon further inspection it appears scrollBehaviour hasnt yet kicked in when the page auto scrolls to the top. Its something else in the browser or vue engine causing this behaviour Commented Dec 9, 2018 at 12:42
  • If the problem exists even when scrollBehavior is commented out, you probably should look for other culprits. Are you clicking a link with href="#"? Commented Dec 9, 2018 at 13:04
  • So strange. I just made a codepen to show this problem. its actually got nothing to do with scroll behaviour. it seems internal to vuejs or the browser codepen.io/anon/pen/bOGqVP Commented Dec 9, 2018 at 13:27

1 Answer 1

5

Browser back button scroll to top is defined by browser. Aparently we can disable that behaviour by adding this line of code

window.history.scrollRestoration = "manual" 

Adding this code will tell browser that we handle the scroll. I only test this in your codepen. Need testing in other browser

Sign up to request clarification or add additional context in comments.

1 Comment

Accepting this as its the only thing so far i have found that works. Great work man. not too sure about browser support yet but working on chrome which is ok for me :) Thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.