Vue router back button prevent navigation to previous domain

832 Views Asked by At

Here is my situation, I have a Vue 3 app using vue-router. On certain pages in my app, there is a back button. If a user navigates to one of the back button pages the page directly, for example /users/123sha256/ and clicks the back button, I had previously been sending them to router.go(-1). However, if a user arrives at this page, and their prior domain is, for example, https://www.google.com and they click the back button, they will be ejected from my Vue app.

I have seen this package on GitHub https://github.com/MaximVanhove/vue-router-back-button and was thinking about doing something like this

const backClick = () => {
  if (this.client || !this.$routerHistory || !this.$routerHistory.hasPrevious()) {
    // probably ssr, or hasn't navigated yet.
    router.push({name: 'home'})
  }

  // 
  // if router.go(-1) is another domain STOP, then Go Home
  //
  
  // otherwise just go back normally
  router.go(-1)
}

Does this seem like it would work? I'm not 100% on what the code would look like but thats the basics of what I have so far.

Some questions I have, and things I would really appreciate some advice / feedback on :

  • Is that package necessary. Or can I use vue-router to perform the same functionality?
  • Is preventing a user from backing out to a previous domain best practice?

Thanks!

1

There are 1 best solutions below

1
Rassulzhan On

I think you can try to measure history.length in different cases. And try to find a pattern of the cases where the user is arrived at the page from different domain and from the vue-router navigation.

When I was dealing with such navigation, I used to create composable function to control back navigation from different pages.

Consider this example:

const backNavigationFnRef = ref(defaultBackNavigationFn)

export const useNavigation = () => {
  const router = useRouter()
  const defaultBackNavigationFn = () => {
      router.go(-1)
  }
  const setBackNavigationFn = (fn) => {
    backNavigationFnRef.value = fn
  }
  const resetNavigationFn = () => {
    setBackNavigationFn(defaultBackNavigationFn)
  }

  return {
   backNavigationFnRef,
   resetNavigationFn,
   setBackNavigationFn
  }
}

Now in most cases, back button will just use defaultBackNavigationFn, and if you want to handle specific pages to always navigate back to a certain page, then use:

_id.vue

<script setup>
 import {useNavigation} from '...'
 const {setBackNavigationFn} = useNavigation()

 setBackNavigationFn(() => {
   // here you can write custom back navigation logic
 })
</script>

in Layout.vue

...
const {backNavigationFnRef} = useNavigation()
...
<Header @onBackBtnClick="() => backNavigationFnRef.value()" />