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

Drawing unusual shapes using canvas arcs in Coffeescript

@.ctx.lineWidth = 20 @.ctx.moveTo(i.x, i.y) @.ctx.arc(i.x, i.y, 3, 0, Math.PI * 2) Can you explain how the code snippet above contributes to the image displayed? ...

Troubleshooting why the ngcheck does not detect if the checkbox is checked

I have come up with a logic, but I am encountering some difficulties in proceeding further. The idea is to use mouseenter/mouseleave events to show/hide a checkbox. If the checkbox is checked, deactivate the mouse and leave function to keep the checkbox v ...

Building a local database using the MVC framework concept

Can a locally stored database be developed using MVC framework principles in javascript and html5? Thank you Ravindran ...

NodeJS Express Application Error: Unable to access /url

I've been troubleshooting this issue for an hour now and I'm stumped. I can't seem to access the specified URL. I created a NodeJs Express app, but when I try to access http://localhost:3000/users/login, I receive the error message Cannot GE ...

Effective implementation of the useReducer hook across various React components to manage form state

My current project is proving to be quite challenging as I navigate through the step-by-step instructions provided. Initially, I was tasked with creating a BookingForm.js component that houses a form for my app. The requirement was to utilize the "useEffec ...

Animating colors with jQuery and shifting SVG shapes to create dynamic and

I am currently working on an svg animation that involves changing the color of the svg to a different color, creating a running light effect. Rather than fading the fill color of the entire svg as commonly seen in examples, I aim to achieve a dynamic trans ...

Executing Javascript dynamically in VueJS: Learn how to run code from a string efficiently

Currently, I am developing a website with VueJS that enables selected users to upload scripts for automatic execution upon page load. For instance, here is an example of the type of script a user may input: <script src="https://cdnjs.cloudflare.com/aja ...

Button for searching through the Bootstrap navigation bar

I'm currently working on adding a search menu to the navbar in two different designs - one for screens below 767px and another for screens above 767px. Although I have been successful in expanding the search bar, I am facing issues with the correct p ...

Is there a way to trigger an Ajax function after individually selecting each checkbox in a list in MVC 4 using Razor syntax?

Is it possible to trigger an AJAX function when a checkbox within the ul below is checked? Each checkbox has a unique name attribute, such as chkbrand_1, chkbrand_2, chkbrand_3, etc. I am able to obtain the correct value using this code: $('.sear ...

Having trouble utilizing the data obtained from an API, encountering errors such as 'data is undefined' leading to nothing displaying on the screen, or 'data.map() is undefined'

I'm relatively new to working with APIs. Although I have successfully made a post, I am creating a new one to clearly outline my issue. My goal is to retrieve posts from the dummyapi. Below is the code snippet that I am using: import React from &a ...

Is it possible to capture and handle browser-specific errors that occur during an AJAX call? I am having trouble locating and capturing these errors

My goal is to thoroughly test an AJAX call for potential errors by deliberately breaking it in various ways. The error callback in jQuery ajax does not provide detailed information like what the browser logs, which is what I need to capture. For example, C ...

Is there a way to trigger a JavaScript function upon checking a checkbox?

Is there a way to trigger a Javascript function when a checkbox within a gridview is checked? protected void ChangeStatusSevenDays_Click(object sender, EventArgs e) { for (int i = 0; i < grdImoveis2.Rows.Count; i++) { GridViewRow RowVie ...

Enhance your user interface by adding a tooltip above a button

I am currently working on creating a button that can copy content from a variable into the clipboard using TypeScript and Material-UI. Here is what I have tried: const [copySuccess, setCopySuccess] = useState(''); const copyToClipBoard = async ( ...

Using jQuery, extract the input value and verify its accuracy. If correct, display the number of accurately predicted results

I am attempting to extract the value from an input field and validate if the answer is accurate. Rather than simply indicating correctness, I aim to analyze and display the number of correct responses alongside incorrect ones. Encountering difficulties wit ...

My React project is altering the direction of my image

Below is the code snippet used to retrieve the user's favorite products import React, { useEffect, useState } from "react"; import { Pagination, Row } from "react-bootstrap"; import { useDispatch, useSelector } from "react-red ...

What is the best way to allocate a unique color to every item within an array?

I've been working on some JavaScript code that pulls a random color from a selection: const colors = [blue[800], green[500], orange[500], purple[800], red[800]]; const color = colors[Math.floor(Math.random() * colors.length)]; Within my JSX code, I ...

Tips for maintaining my Countdown timer even after a page refresh

I'm currently tackling JS and I've hit a roadblock. I have successfully created a countdown timer, but now I want it to continue running even after the page is reloaded. I decided to use sessionStorage to store the countdown value and check if t ...

Extract Information from a Website

Is there a way to extract data from another website using JavaScript and save it into a .TXT or possibly an XML file? If JavaScript is not the best solution, I am open to other suggestions. I am specifically interested in extracting the price and item na ...

Hiding a Component: Achieving Smooth Behavior with Timer and onPress

My goal is to create a user interface where tapping the screen displays a <TouchableWithoutFeedback> component, which should automatically disappear after 4 seconds. Additionally, I want the user to be able to tap on the displayed component to hide ...

Automatically substitute a term with a clickable link

Is there a way to automatically turn every word into a hyperlink? I have specific words that need to be linked. For example, I want Ronaldo (Only for the First Appearance) to link to a certain page. However, my attempted method did not work. <p> Ro ...