0

Context

I have this LightGallery plugin, and I noticed that when it is in fullscreen, clicking on the previous page button will not close the LightGallery but go "silently" to the previous page without the user to be aware of it.

In my case, I am building an SPA using VueJS and VueRouter, and when the user closes the LightGallery after clicking the previous page, it is confusing because the user expected to get back where he/she was.

I know that VueRouter has navigation guards, but I miss one feature, to easily know if the user is going back or not.

I am using VueRouter in "history" mode.

As I use the "history" mode, I guess this explains why the lg-hash plugin for LightGallery is of no help. It only appens a hash to my route, but the VueRouter is working independently of this hash.

Question

How to know if the user is going to the previous page using VueRouter?

In "history" mode, VueRouter is using the History API. Is there anyway to use it to have a clue? Or should I eventually store manually the history and process it at each route change?

I have found that we can listen to previous/next page using window.onpopstate = function() {}, but can I exclusively check for the previous page only using this method?

Anwar
  • 4,162
  • 4
  • 41
  • 62
  • You could store the `routeFrom` in a variable, or in the `routeTo.meta` property, using the `router.afterEach` global after hook, but instead I think you should use the `beforeRouteLeave` in-component guard and close the LightGallery if it's open. That makes more sense to me, unless I'm missing something. – Ricky Ruiz Nov 01 '19 at 19:23
  • It makes perfect sense, the only thing that bugs me is that this event will be fired even if the user clicks the "forward page" browser button, which I want to prevent. I hoped there was some existing state of the art way to detect a previous page event using VueRouter. – Anwar Nov 01 '19 at 19:37

1 Answers1

2

In my router instantation I have:

const router = new Router({
 mode: "history",
 scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      to.meta.fromHistory = true;
      return savedPosition;
    } else {
      return { x: 0, y: 0 };
    }
  },
 // (...)

However, as you mentioned, there's no clear way to catch whether that's a back or a forward navigation taking place.

As per the official documentation:

The scrollBehavior function receives the to and from route objects. The third argument, savedPosition, is only available if this is a popstate navigation (triggered by the browser's back/forward buttons).

Michal Paczes
  • 199
  • 11