Vue route guards not triggering when I manually change the url

Hi All,

I am trying to prevent users from manually changing url in the browser. If they try to manually change the url I have to redirect them back to the previous page. i.e. if the url is localhost:8000/home-view and if they try to change it manually by removing “-view” to localhost:8000/home, I should be redirecting them back to localhost:8000/home-view. I am using typescript , vue-class-component.

So I did the following :-

  1. Registered the hooks.

Component.registerHooks([
‘beforeRouteLeave’,
]);

  1. In the code.

beforeRouteLeave(to,from,next:any){
next(false);
}

Unfortunately this is not working for manual change in URL’s . Programatically if I add a button which on click does a router push to a different page, this route guards is triggering. But not in the case of manual changes. Am I missing something?

The thing is, that if you try to use the hook beforeRouteLeave then it also triggers, when programmatically changing the route–$router.push('/home') for instance.

So, the first thing what came into my mind would be, to set a global variable or store (Vuex) and set a bool whether or not, you have programmatically changed the route.

If so, the user can continue, if not, if he did manually change it, then he is going to be redirected to whatever route he was.

Like

Your store

const store = {
  shouldPass: false
}

const getters = {
  // True if you have changed the route manually
  // False if the user changed it himself or herself
  getShouldPass (state) {
    return state.shouldPass
  }
}

Your component

import { mapGetters } from 'vuex'

export default {
  ...
  ...mapGetters('routeLookup', ['getShouldPass']),
  beforeRouteLeave (to, from, next) {
     next(vue => {
       if (vue.getShouldPass) {
         // Redirect to the path you want the user to be
       } else {
         // Let him stay on the current page
       }
     })
  }
}