What is the method for obtaining the previous URL in the route history that is different from the current URL?

I have implemented a button on my application that allows the user to navigate back to the previous page.

Here is how it's set up:

<button ng-click="goBack()">Go back</button>

$scope.goBack = function() {
    $window.history.back();        
}

However, I am looking to modify this functionality so that the button takes the user to the previous URL that is different from the current URL, rather than just the previously visited page (which may have the same URL as the current one).


For example:

  • If I visit /home, then /products, followed by another /products, and then one more /products
  • I would like the button to take me back to /home.

Is there a way to achieve this and retrieve the first URL that is different from the current one?

Answer №1

For security reasons, you won't be able to access the native history URLs, but there's a workaround using Angular. You can maintain your own history records with a service like myHistoryService:

app.run(function($rootScope, $location, myHistoryService) {
    $rootScope.$on('$routeChangeStart', function(ev, next) {
        var path = $location.path();
        myHistoryService.push(path);
    });
});

In myHistoryService, you have the flexibility to push to an array or implement any custom logic you need.

This approach is suitable if you only require the history functionality within your domain.

Answer №2

Managing navigation within your Angular app can be easily achieved by tracking state changes and URLs.

To do this, you can listen for the stateChangeSuccess event to monitor when the state changes, and keep a count of how many times the URL remains the same. When you want to navigate back to the previous unique URL, simply use window.history.go(-X), where X represents the number of identical URLs.

Below is a simple example (using $rootScope for simplicity) to demonstrate this concept:

angular.module('YourModule').run(function() {
    var lastUrl, counter;
    $rootScope.$on('$stateChangeSuccess', function(event, toState) {
        if (lastUrl != toState.url) {
            counter = 1;
            lastUrl = toState.url;
        } else {
            counter++;
        }
    });
    $rootScope.goBack = function() {
        $window.history.go(-1 * counter);
    };
});

Answer №3

1.

If you want to navigate the browser back to the previous page, you can use the function window.history.back();. However, it is not possible to access the URL of that page for security reasons. Being able to do so would pose a risk of spying on users as they visit your website.

On the same domain, you can utilize document.referrer to obtain the previous URL.

2.

To interact with the browser history, you can make use of the History Object.

You can access this object using window.history, which will provide an array of history items. By comparing the current location window.location.href with the data from this object, you can manage the browsing history effectively.

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

The HTML and JavaScript implementation of the Game of Life is experiencing technical difficulties

I attempted to create my own version of the Game of Life using HTML canvas and JavaScript. With the aid of various online tutorials, I was able to write a piece of code that I am still confident in. However, upon launching the HTML page in the browser and ...

Guide on how to transform form data into an object containing nested properties

Considering the inputs provided below: <input name="person[1]['first']" /> <input name="person[2]['first']" /> <input name="person[3]['first']" /> The objective is to convert this into an object structure a ...

Implementing event handling for external modules using on method in Node.js

I have been utilizing the request module (available at https://www.npmjs.com/package/request) for executing a series of http requests in my application. However, I am currently facing an issue while attempting to integrate a logging feature into it. I am s ...

Using $q.all function in a controller to fetch data from a service and receiving an

For a considerable amount of time, I have been facing some challenges with an API call. Even though the console.log in my service is returning the necessary data, the controller seems to receive an empty object. I suspect there might be an issue with how I ...

Tips for handling promise resolution with $resource in AngularJS

My controller has an activate method that waits for promises to resolve before moving forward. function activate() { var promises = [getNodesGroup(), getNodes()]; common.activateController(promises, controllerId) .then(function () { ...

Showing a tooltip in Angular when a button is disabled

<button [disabled]="(!dataConceptSummmaryFlag || dataConceptSummmaryFlag === false) && (!selectedLOBFlag || selectedLOBFlag === false) && (!adsListFlag || adsListFlag === false)" class="lmn-btn lmn-btn-primary" ...

There may be instances where data is null in Java Spring and React JS

My goal is to store all data using react.js and Java Spring. I have sent data via REST, but one of the data classes is coming up as null in the MongoDB collections. I have checked to ensure that all data types are the same but I am unable to identify and r ...

Using ASP.net MVC 4 to Implement Validation with Bootstrap Modal and PartialView

After switching from a simple View with validation to using a bootstrap modal and PartialView in my application, I encountered some issues. The client-side validation no longer works and the server-side validation redirects me to a new page instead of disp ...

What is the best way to access nativeElements during the ngOnInit lifecycle hook?

Assume in my angular script I have the ability to access an HTML element with viewChild('someDiv') or constructor(private elem: ElementRef){}. When my angular component loads, I want to immediately retrieve a property of that element and store it ...

Display the accurate duration based on the dates selected in an HTML form automatically

If someone has office hours on Monday, Wednesday, and Friday from 7:00 am to 7:00 pm, and on Tuesday and Thursday from 10:00 am to 9:00 pm, the dropdown menu should display only the timings of 7:00 AM to 7:00 PM if the selected date is a Monday, Wednesda ...

What could be causing the misalignment of my request and response messages?

Currently, I am going through a Node.JS basics book and have successfully created two programs - one responder and one requester. The responder: "use strict"; const fs = require("fs"); const zmq = require("zmq"); const responder = zmq.socket("rep"); // ...

Exploring the realm of unit testing in the NestJS CQRS architecture journey

We're currently working on writing unit tests using Jest for our application and are facing difficulties in testing sagas. Specifically, we're having trouble testing the saga itself. During our unit testing process, we've encountered an iss ...

Unable to detect JavaScript in Chrome Developer Tools

I am experiencing a strange issue where my JavaScript code is not showing in the sources window. When I include a debugger statement in my JS and then reload the page, it successfully breaks and I can view the JavaScript code. However, the tab is labeled ...

Why isn't the Nunjucks extends directive functioning when the template is stored in a different directory and being used

I have successfully integrated nunjucks templating into my express app. Below is the directory structure of my project: . nunjucks-project |__ api |__ node_modules |__ views |__ templates |__ layouts |__ default.html ...

Display the <div> element at the current scroll position on the page

Alright, I have a challenging question for you! I don't have the ability to search the internet for this one because I can't quite put it into words. All I have are some images and wild guesses on how it's done. Maybe you'll find it int ...

Generating a JSON object on the fly in a React Native application

There have been similar questions asked in the past like this & this. After looking at those SO questions, I came up with this code. As a newcomer to React Native and Javascript, I am facing two issues. 1. I'm trying to structure my data like this ...

What's the best way to align divs vertically in a compact layout?

Update The reason I require this specific behavior is to ensure that all my content remains in chronological order, both on the web page and in the HTML structure. This way, even if the layout collapses into a single column on smaller screens, the content ...

How to Implement a Loop Inside a JavaScript Alert or Prompt?

Seeking clarity: Is it possible to embed code into an alert() or prompt()? For example, is there a way to include a loop or add data to the alert() or prompt just before execution or during execution? -Appreciate any help ...

What is the best way to create a continuous loop of images on a never-ending

Many discussions cover similar topics, but I have not yet found a solution to my specific question. Currently, I am working on creating a model for a website and I am interested in incorporating an infinite rotating gallery with a limited number of images ...

Struggling with Mocha, supertest, and passport when testing authenticated routes with JWT authentication

I've been experimenting with testing authenticated routes in Mocha, but I've run into an issue where the user created in the `before` or `beforeEach` hooks doesn't persist. Here's a snippet from my test.js: const should = require(&apo ...