How can I retrieve the URL of the previous page from the history object in all browsers?

Can we retrieve the URL of the previous page from the history object? I've seen references to history.previous, but it appears to be either undefined or protected based on my observations.

Answer №1

To retrieve the previous webpage visited, you can access it using the document.referrer property instead of the history object. However, keep in mind that there is no universal method to achieve this as support for different properties may vary across browsers.

Answer №2

Accessing browser history is a serious security violation as it would allow anyone to view the browsing history of users.

It may be possible to create a Browser Helper Object for IE and other browsers that provides access to browser history, similar to the google toolbar. However, this would require user permission to run on their machine.

There are unethical methods to access browser history, but these should not be pursued. For more information, check out this link.

Answer №3

As many have mentioned, it's generally not possible to track browser history. However, I've come up with a workaround by saving each page visited in the localStorage. This way, you can create your own browsing history...

function writeMyBrowserHistory(historyLength=3) {
  // Store last historyLength page paths for use in other pages
  var pagesArr = localStorage.myPageHistory
  if (pagesArr===null) { 
        pagesArr = [];
  } else {
        pagesArr = JSON.parse(localStorage.myPageHistory);
        pagesArr.push(window.location.pathname)  // can use whichever part, but full URL needs encoding
  }
  if (pagesArr.length>historyLength) {
        // truncate the array
        pagesArr = pagesArr.slice(pagesArr.length-historyLength,pagesArr.length)
  }
  // store it back 
  localStorage.myPageHistory = JSON.stringify(pagesArr);
  // optional debug
  console.log(`my page history = ${pagesArr}`)
}

function getLastMyBrowserHistoryUrl() {
  var pagesArr = localStorage.myPageHistory
  var url = ""
  if (pagesArr!==null) { 
    pagesArr = JSON.parse(localStorage.myPageHistory);
    // pop off the most recent URL
    url = pagesArr.pop()
  }
  return url
}

Simply include the following JavaScript on every page:

writeMyBrowserHistory()

To retrieve the last page visited:

var lastPageUrl = getLastMyBrowserHistoryUrl()

Keep in mind that localStorage can only store strings, hence the need for JSON parsing.

If you spot any issues in the code, feel free to let me know as I've formatted it for clarity from the original version.

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

A guide on setting up fixed row numbers in MUI-X DataGrid

One challenge I am facing is rendering the row numbers in a table so that they remain static even when columns are sorted or filtered. I attempted to use the getRowIndexRelativeToVisibleRows method of the grid API, but unfortunately, it does not work as ex ...

How can I implement jQuery Ajax to handle multiple elements on a single webpage?

I recently created a page where users can add items to their "favorites" list using the following JavaScript code: $(function(){ $('.doit-01234').click(function (e) { e.preventDefault(); $.ajax({ url: "https://www.domain. ...

Can you please provide guidance on how to dynamically add number values from an array to a select tag in Vue.js?

I'm trying to populate a select tag with options from an array variable that contains arrays of number values. However, the values being output appear to be blank. Here is the HTML code: <select required id="dropDown"> <option>Sele ...

Should a React application perform a complete refresh when a file is reloaded?

Recently, I delved into the world of React and learned about one of its key benefits: updating only the necessary DOM elements. However, as I began building an app from scratch, I encountered a situation where every time I saved the .js file, it resulted ...

Create a dynamic process that automatically generates a variety of div elements by using attributes from JSON data

Is there a way to organize the fixtures from this data into separate divs based on the matchday attribute? I've tried using Underscore's groupBy function but I'm unsure how to dynamically distribute the data into individual divs for each re ...

Console command to change paragraph tag color---Modifying the color

I am attempting to change the color of all paragraph tags on a webpage to white by utilizing the console. My initial attempt was: document.p.style.color = 'white'; However, this method did not have the desired effect. Interestingly, I have had s ...

How can XML data be effectively showcased on a website?

I have a service that generates XML files every 10 seconds with server information. I am seeking a solution to showcase this data on a webpage. After researching online, it appears that utilizing AJAX would be beneficial as it permits the loading of dynam ...

AngularJS - "Refrain from replicating items in a repeater"

I am facing an issue with creating HTML textarea elements for each member of an array. Despite consulting the AngularJS documentation and attempting different track by expressions, I am unable to render them. The problem arises when a user inputs the same ...

Transmitting information to the service array through relentless perseverance

I need assistance finding a solution to my question. Can my friends help me out? What types of requests do I receive: facebook, linkedin, reddit I want to simplify my code and avoid writing lengthy blocks. How can I create a check loop to send the same ...

I am looking to incorporate a new "ID" column into my mui data grid table in ReactJS that will incrementally count from 0 to the total number of rows

When displaying data from an API in a datagrid table component with multiple columns, it is necessary to include a column for the ID which should have values ranging from 0 to the number of rows. Currently, the Object_id is being displayed in this cell. T ...

Improving the functionality of multiple range slider inputs in JavaScript codeLet me

Is it possible to have multiple range sliders on the same page? Currently, all inputs only affect the first output on the page. Check out an example here: http://codepen.io/andreruffert/pen/jEOOYN $(function() { var output = document.querySelectorAl ...

Eliminate parameter from URL

Here is the URL I am working with: http://my.site/?code=74e30ef2-109c-4b75-b8d6-89bdce1aa860 My goal is to redirect to this URL: http://my.site#/homepage To achieve this, I use the following code snippet: import { push } from 'react-router-redux& ...

"How to dynamically fill a text input field from a table using jQuery when a specific value is selected, potentially involving multiple rows (possibly

Scenario I created a form that allows users to place orders for articles. These articles are displayed in a table within another form, where each article is listed with its code, description, and price. The goal is for users to select an article from th ...

Is it possible to use window.print() to print the entire contents of a DIV with both horizontal and vertical scroll bars?

In my code, I have a div that contains both horizontal and vertical scrollers. Whenever I try to print the content inside this div using the window.print() method, it only prints the visible portion of the div. Here is the code snippet that I have attempte ...

The compilation of the module has encountered an error with the PostCSS loader. There is a SyntaxError at line 2, character 14 indicating an unknown

I am developing an Angular 8 application. Currently, I am incorporating AlertifyJs into my project. In the styles.css file of Angular, I have imported these libraries: @import '../node_modules/alertifyjs/build/alertify.min.js'; @import '. ...

The canvas game's animation can only be activated one time

I am currently working on designing a straightforward canvas game: Here is the code snippet located on CodePen var canvas; var ctx; var x = 300; var y = 400; var r = 0; var mx = 0; var my = 0; var WIDTH = 600; var HEIGHT = 400; function circle(x,y,r) ...

Express.js encountering an `ERR_HTTP_HEADERS_SENT` issue with a fresh Mongoose Schema

My Objective Is If data is found using the findOne() function, update the current endpoint with new content. If no data is found, create a new element with the Schema. Issue If there is no data in the database, then the first if statement throws an ERR_H ...

Unauthorized access detected during ajax request triggered by onpaste event

Recently, I encountered an issue with my asp.net mvc website where an ajax call to the server stopped working in IE 11, despite previously working fine in IE 8. The error message pointed to an access denied exception in jQuery 1.7.1 at h.open(c.type,c.url, ...

Securing the Firebase Admin SDK JSON file within a NextJS project for optimal protection

I'm currently working on a NextJS app that uses the Firebase Admin SDK, but I'm unsure of where to securely store the JSON file containing all the keys. It seems that integrating secret keys in JSON files with an .env.local file is not possible. ...

Iterate over each option in a select dropdown menu and modify them

Below is the test code snippet I am working with: ID = { CreatedBy: { id: 'createdBy' }, ModifiedBy: { id: 'modifiedBy' } } Profile = { All: { text: 'All', val: 0 }, Sys: { text: '<a href="/cdn-cgi/l/emai ...