SoFunction
Updated on 2025-04-05

Methods to prohibit web pages from returning to previous page in VUE3

You can use the following method to prohibit web pages from returning to the previous page in Vue 3:

The first type: listen to return events

Use the return listening event, which is triggered when the user clicks the return button, and then use () to return to the next page after triggering.

The code is as follows:

<script language="javascript">
('popstate', function () {
();
});
</script>

This method cannot prevent the browser from returning to the previous page, so it will cause the page to flash, so this method is not recommended.

The second type: modify the history in the page

Use the() method to add the current URL to the browser history, overwriting the URL of the previous page.

If we set the parameter to empty, it is equivalent to clearing the record on the previous page, and we can achieve the purpose of not being able to return to the previous page.

For example, add (null, null, );

The code is as follows:

<script setup>
onMounted(()=>{
(null, null, );
})
</script>

There will be no flash in this method, but if you are in multi-page applications, you will find that using this method can only take effect on the current page.

The third type: modify the history in the route

Clearing the previous page data in the route afterEach makes the route unable to jump, thus achieving the purpose of prohibiting the web page from returning to the previous page.

Notice:

(null, null, ) Don't add it to beforeEach, it won't work here. Because this is executed before the jump, the route can still get the previous page data at this time, thereby completing the jump to the next page.

For example, add the following code in:

import { createRouter,createWebHistory } from "vue-router";
const router = createRouter({
history: createWebHistory(),
routes:[
{
name: 'test1',
path:'/test1',
component:() => import('../components/'),
},
{
name:'test2',
path:'/test2',
component:() => import('../components/')
}
]
})
// Execute every time the routing jump is performed(function(to,from,next){
// Note that writing here will not disable return function, because this is executed before jumping, and the route can also get the data on the previous page before jumping})
// Execute after routing jump(function(to,from){
// Clear the data from the previous page after jumping(null, null, );
})

You can also add conditions that prohibit jumping in afterEach, such as limiting only specific pages, or performing other operations.

This is the article about how to prohibit web pages from returning to the previous page in VUE3. For more related contents of vue3 prohibiting web pages from returning to the previous page, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!