Home > Software design >  (vue router) disabling browser back and forward arrows, with warning
(vue router) disabling browser back and forward arrows, with warning

Time:11-10

I'm creating a multipage quizz, so I need the user not to be able to go back to the previous page. So I wrote:

const router = createRouter({
  history: createMemoryHistory(),
  routes
});

It's working (navigation is disabled), but it the user hits back a few times, it ends up leaving the page without warning.

Is there a way to add a warning for the user?

Thanks in advance

Regards

CodePudding user response:

You could use a global navigation guard to check if the user is navigating to a recognised route or not, and prompt for confirmation before navigating away.

Something like:

router.beforeEach((to, from) => {
  const route = this.$router.resolve(to)

  if (route.resolved.matched.length) {
    // the route exists, return true to proceed with the navigation
    return true
  }else{
     //the route does not exists, prompt for confirmation
    return confirm("Are you sure you want to leave this site?")
  }
})

CodePudding user response:

In turns out the solution is outside Vue/VueRouter:

window.addEventListener('beforeunload', function (e) {
    e.preventDefault();
    e.returnValue = '';
});

Now the Vue-specific navigation is not recorded by the browser, and clicking the Back arrow displays the browser's built-in message.

  • Related