简体   繁体   中英

Return customer to same position when clicking browser's back button

What I am trying to do? I want to remember the current position of the user on the page, so once s/he navigates to another page and then comes back using the browser "Back" button to scroll to that position. Please note that I need to maintain this behaviour only when the user clicks on the browser back button.

How I am trying to achieve it? When the user clicks on an href I was using a method to replace the state. The page was then re-directed to the right place.

window.history.replaceState({ scrollToProduct: true, productCode: 'produt-XXXX' }, document.title, `${window.location.href}?product-code=produt-XXXX`);

I was then trying to register popstate listener in my App.vue

beforeMount() {
        window.onpopstate = function(e) {
            console.log(e);
        };
    }

Where my issue is? Unfortunatelly the popstate listener doesn't get attached, so I can't capture the click of the "Back" button.

I've also tried using router.push.

this.$router.push({ name: 'NameOfComponent' });

What is interesting is that I get navigated to the other page (without page reload), and when I click on the back buttton the popstate does work. I am unfortunatelly not able to pass anything into the hisotry state.

Can someone help with this?

PS: I am not using SPA, but rather refresh on each page.

You can't use vue-router if you don't register it correctly or if you don't use Vue as an SPA.

What you need is history.back() or history.go(-1).

https://developer.mozilla.org/en-US/docs/Web/API/History/back

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM