Search code examples
javascriptbrowser-history

Javascript; Browser history; Is there cross-browser way to read previous page url( history.go(-1) ), and second last page ( history.go(-2) )?


I need to dynamically get and process url's of previous two pages. Tried to do something like this but without luck(used Chrome, but I need solution for all browsers):

console.log(window.history.entries[window.history.index - 2]);

The only object that I can successfully get is "history.lenght".

This gives "undefined" multiple times too:

for (var i = window.history.length; i >= 0; i--) {
    console.log(window.history[i]);
}

update: I'm adding [Back] button and there is popup on server, that breaks my code. If popup appeared, I call history.go(-2). I noticed that it always appears in Chrome and Opera, and created workaround. But it is bad solution and I'm not sure it covers all situations, that's why I need to compare previous urls

if (navigator.userAgent.search("Chrome") > -1 || navigator.userAgent.search("OPR") > -1) {
    // insert conditional Chrome code here
    console.log("Go Back button: Chrome or Opera detected, go two pages back.");
    history.go(-2);
    return false;
} else {
    console.log("Go Back button: Browser is not Chrome, go one page back.");
    history.go(-1);
    return false;
}

Solution

  • Put this on all the pages of your website..

    localStorage.setItem('2PagesAgo', localStorage.getItem('lastPage'));
    localStorage.setItem('lastPage', localStorage.getItem('thisPage'));
    localStorage.setItem('thisPage', location.href);
    

    Then to get the last and previous pages just do..

    var lastPage = localStorage.getItem('lastPage');
    var 2PagesAgo = localStorage.getItem('2PagesAgo');
    

    This will allow you to track the last 2 pages a user visits on your site. Any browsing the user did outside of your site is none of your business. :)