Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if the user can go back in browser history or not

Tags:

javascript

I want using JavaScript to see if there is history or not, I mean if the back button is available on the browser or not.

like image 770
CodeOverload Avatar asked Aug 27 '10 21:08

CodeOverload


People also ask

How do I view windows history?

Manage activity history settingsIn Windows 10, select Start , then select Settings > Privacy > Activity history. In Windows 11, select Start , then select Settings > Privacy & security > Activity history.

How do I check stack history?

history object allows you to access the history stack of the browser. To navigate to a URL in the history, you use the back() , forward() , and go() methods. The history. length returns the number of URLs in the history stack.


2 Answers

Short answer: You can't.

Technically there is an accurate way, which would be checking the property:

history.previous 

However, it won't work. The problem with this is that in most browsers this is considered a security violation and usually just returns undefined.

history.length 

Is a property that others have suggested...
However, the length doesn't work completely because it doesn't indicate where in the history you are. Additionally, it doesn't always start at the same number. A browser not set to have a landing page, for example, starts at 0 while another browser that uses a landing page will start at 1.

alt text

Most of the time a link is added that calls:

history.back(); 

or

 history.go(-1); 

and it's just expected that if you can't go back then clicking the link does nothing.

like image 180
McAden Avatar answered Sep 17 '22 10:09

McAden


There is another way to check - check the referrer. The first page usually will have an empty referrer...

if (document.referrer == "") {     window.close() } else {     history.back() } 
like image 44
Ron Reiter Avatar answered Sep 19 '22 10:09

Ron Reiter