EDIT-2: None of the answers seem to work. Not even the one I previously marked as the answer of this question. Any help is appreciated. Thanks.
check window.history.length or simply, history.length
EDIT: some browsers start their history with 0, others with 1. adjust accordingly.
if it has a value of 1, it means it's the first page in that window/tab - then you can have JS redirect you.
<script>
function backAway(){
//if it was the first page
if(history.length === 1){
window.location = "http://www.mysite.com/"
} else {
history.back();
}
}
</script>
<a href="#" onClick="backAway()">Back</a>
Added a new answer to display the code formatted:
The thing is that you were checking for document.referer, because you were in ff it was returning always true, then it was navigating to http://mysite.com. Try the following:
function backAway(){
if (document.referrer) {
//firefox, chrome, etc..
i = 0;
} else {
// under ie
i = 1;
}
if (history.length>i)
{
// there are items in history property
history.back();
} else {
window.location = 'http://www.mysite.com/';
}
return false;
}
How about using the history replacement function to add the site into the browsers history?
Try executing the following as soon as the window loads-
history.replaceState("example", "title", "http://www.example.com");
This should hopefully make it so even if it is the first page they have accessed, the URL you define in the code will be what they're taken to when they click back.
You need to check both document.referrer
and history.length
like in my answer to similar question here: https://stackoverflow.com/a/36645802/1145274
this seems to do the trick:
function goBackOrGoToUrl() {
window.history.back();
window.location = "http://example.com";
}
Call history.back() and then change the location. If the browser is able to go back in history it won't be able to get to the next statement. If it's not able to go back, it'll go to the location specified.
simply use cookies to store your visited page list.
and apply some if else.
EDIT: also use ServerVariables HTTP_REFERER.