Is there a way to access the history of Vue routers?

I am looking for a way to determine if the Vue router has additional entries in its history that can be navigated back to. This information is crucial for deciding whether or not to execute the exit app function. The app should only navigate back to previous pages as long as it is possible, but once it reaches the final page, it should exit.

Answer №1

Encountering a similar issue, I had to manage both an angularjs and vue.js app running simultaneously. The approach I took was to switch to the angularjs app once the vue.js history stack was empty. Below is the solution I implemented using vuex:

/** store/history.ts */

import { clientRouter } from '@/views'
import { Route } from 'vue-router'
import { ActionTree, GetterTree, Module, MutationTree } from 'vuex'
import { IRootState } from '.'

export interface IHistoryState {
    history: Route[]
}

const historyState: IHistoryState = {
    history: []
}

const getters: GetterTree<IHistoryState, IRootState> = {
    history: state => state.history
}

const mutations: MutationTree<IHistoryState> = {
    pop: state => state.history.pop(),
    push: (state, route: Route) => state.history.push(route)
}

const actions: ActionTree<IHistoryState, IRootState> = {
    back: context => {
        const history = context.state.history
        if (history.length === 1) {
            window.location.href = '/angular.html'
        }
        else {
            clientRouter.back()
        }
    },
    record: (context, route: Route) => {
        const history = context.state.history

        // Reloading same page
        if (history.length && history[history.length - 1].name === route.name) {
            context.commit('pop')
            context.commit('push', route)
            return false
        }
        // Going back
        else if (history.length > 1 && history[history.length - 2].name === route.name) {
            context.commit('pop')
            return false
        }
        else {
            context.commit('push', route)
            return true
        }
    }
}

export default {
    state: historyState,
    getters,
    mutations,
    actions,
    namespaced: true
} as Module<IHistoryState, IRootState>

Utilizing clientRouter due to SSR, but any router can be used. The code is in typescript, but can be converted to vanilla JS upon request. By following this method, navigation should always happen through the designated action here. To keep track of history, I added the following code to the main app component:

/** app.vue */

@Action('history/record') recordHistory: (to: Route) => forward:boolean

@Watch('$route')
function (to: Route) {
    // Push to history
    this.recordHistory(to)

    // Analytics
    analytics.trackPageView()
}

Answer №2

It seems like there is some confusion in your question regarding the term "As long as the app can go back to a previous page" - are you referring to any page in the browser's history or within your application?

If it's the former, you can achieve this by using:

history.back();
app.exitProcess();

This way, the script will only execute exitProcess if the browser cannot go back in its history.

You may also consider checking out document.referrer, although it might be empty or undefined most of the time.

On the other hand, if you meant the latter scenario, I suggest maintaining a history state to track the last 'back' action within your app and when it would lead to exiting the app and navigating to another site.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to address Peer dependency alerts within npm?

Here is a sample package.json that I am using for my application: dependencies : { P1 : “^1.0.0” // with peer dependency of p3 v1 P2 : “^1.0.0” // with peer dependency of p3 v2 } P1 and P2 both have peer dependencies on ...

Embedding a YouTube video in a view player using HTML5

So I've got a question: can you actually open a youtube video using an HTML5 video player? I'm looking for a more mobile-friendly way to watch youtube videos, and my idea was to upload a thumbnail image and then set up an onclick function to disp ...

Create a unique type in Typescript that represents a file name with its corresponding extension

Is there a way for me to specify the type of a filename field in my object? The file name will consist of a string representing the name of the uploaded file along with its extension. For instance: { icon: "my_icon.svg" } I am looking for a ...

How can we organize and display the data from two linked arrays, one containing player names and the other containing

Looking for help on how to rank 3 players based on their scores using arrays. I've hit a roadblock and need guidance! Here's a brief example: Player 1 : Taylor Score Taylor : 15 Player 2 : Jordan Score Jordan : 20 Player 3 : Alex Score Alex : ...

What is the process for constructing an object to resemble another object?

After collecting input data, I have created an object based on those values. Here is an example of the generated object: var generate_fields = { name: "Mike", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b4d9dddf ...

jquery counter is malfunctioning

I noticed a strange issue with the counters on my website. They count up as expected when the page loads, but for some reason, when the screen width shrinks below 800px, they don't start automatically. However, if I quickly scroll to where the counter ...

Setting a background image as a variable in Vue.js

I am currently working on a vue.js component that includes a div.icon: Vue.component('obj', { props: ['img', 'name'], template: '<div><div class="icon"></div> {{ name }}</div>' }) While ...

Create a JavaScript JSON object using a for loop

I am working on creating an object similar to this var flightPlanCoordinates = [ {lat: 37.772, lng: -122.214}, {lat: 21.291, lng: -157.821}, {lat: -18.142, lng: 178.431}, {lat: -27.467, lng: 153.027} ]; Here is my attempt so far for (i = 0; ...

Steps to activate the Back button when utilizing WebView in Nativescript-Vue

As a beginner in nativescript-vue development, I am currently working on implementing the Android side code. I have managed to successfully insert WebView, but faced an issue where the app gets terminated immediately when I touch the back physical button o ...

Is there a way to prevent the annoying "Reload site? Changes you made may not be saved" popup from appearing during Python Selenium tests on Chrome?

While conducting automated selenium tests using Python on a Chrome browser, I have encountered an issue where a popup appears on the screen after reloading a page: https://i.stack.imgur.com/gRQKj.png Is there a way to customize the settings of the Chrome ...

Employing promises for fetching data via XHR results in a promise that is still pending

Currently, I am experimenting with promises to handle asynchronous requests using XHR. Interestingly, I noticed that when I try to log the result within the .then function, it works perfectly fine. However, if I attempt to log it outside of this scope, it ...

What is the process for displaying data submitted through a form on page B to page A using Node and Express?

Dealing with the issue Hello everyone. I've been struggling for the past 30 minutes trying to figure out the rendering method problem I'm facing. Whenever I try to post data through a form from Page A and then render that data on Page B, I keep ...

Node.js variable initialization

Here's the issue I'm facing: in this function, I'm attempting to return an array of objects. When I use console.log within the forEach loop, the array is populated as expected. However, just before my return statement, it appears empty. And ...

JavaScript event in Chrome extension triggers a browser notification and allows for modification using a specific method

I am currently developing a Chrome extension that is designed to take specific actions when system notifications appear, with the main goal being to close them automatically. One example of such a notification is the "Restore pages?" prompt: https://i.sta ...

Guidelines for cycling through a series of HTTP requests and effectively saving the data from each cycle into an array

Utilizing Spotify's API search feature, I am working with an array of SongSearchParams that consist of title and artist parameters: export class SongSearchParams { public title: string; public artist: string; constructor(title: string, a ...

After the initial iteration, the .length function ceases to function properly when

A validation method is set up to check the length of a user input field. It functions properly on the initial try, but does not update if I go back and modify the field. $("#user").blur(function () { if ($("#user").val().length < 3) { $("#userval ...

Organize information within a single column of a table according to the heading using Angular

I have been working on implementing a sorting operation in a table for one or multiple columns. Consider the following table: When clicking on Heading 1, only Data 1 and Data 2 should be sorted. When clicking on Heading 2, Data 3 and Data 4 need to be sor ...

Unable to execute the action specified in the store sub-file

In my /store/index.js file, I have the following code: import Vue from "vue"; import Vuex from "vuex"; import auth from "./modules/auth"; Then in /store/modules/auth.js, I define the login action like this: export const actions = { login({ commit, dis ...

Using Angular UI Router to Access $scope Beyond the Scope of the UI View

Looking for a way to access $scope outside the UI view in my todo app. The structure is simple, with three panels as shown in this design For the full code, visit here I need to access the to-do detail on the third panel using $rootScope, which currently ...

Saving the index.html file to disk when the button is clicked

Is there a way to export the current HTML page to a file? I have attempted to achieve this using the following code, but it only works when the page is loaded and not with a button click. <?php // Start buffering // ob_start(); ?> <?php file_pu ...