JaChNo
JaChNo

Reputation: 1573

Vue router navigation guard prevent url from being changed

I'm using a vuejs navigation guard to do some checks to check if a user is valid to enter a page. If the user doesn't meet the criteria I want the auth guard to return false which it currently does. However, when this is done the browser url gets set back to the previous url I came from. I don't want this behaviour instead I want the browser url to stay the same but still keep the user unable to use the page.

The reason I want this is because when the user hits refresh I want it to stay on the same page. I know this is intended vuejs behaviour for the router but I'm hoping to find a way around it. Here is the code for auth guard.

function guardRoute (to, from, next) {

    if (window.$cookies.get('kiosk_mode') === new DeviceUUID().get()) {
        return next(false)
    }

    return next()

}

Upvotes: 0

Views: 2071

Answers (2)

MJ_Wales
MJ_Wales

Reputation: 893

To reject a navigation but to not reset the url to its previous state you can reject the navigation with (requires vue 2.4.0+):

next(new Error('Authentication failure'));

And if you don't have router error handling then you need to include:

router.onError(error => {
    console.log(error);
});

See documentation for more details: https://router.vuejs.org/guide/advanced/navigation-guards.html#global-before-guards

Upvotes: 1

Jamie Woods
Jamie Woods

Reputation: 579

Try this history.pushState({}, null, '/test') before the return next(false);

Upvotes: 0

Related Questions