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.
The following code did the trick for me.
html:
Back
js:
home_url = [YOUR BASE URL];
pathArray = document.referrer.split( '/' );
protocol = pathArray[0];
host = pathArray[2];
url_before = protocol + '//' + host;
url_now = window.location.protocol + "//" + window.location.host;
function goBackOrGoHome(){
if ( url_before == url_now) {
window.history.back();
}else{
window.location = home_url;
};
}
So, you use document.referrer to set the domain of the page you come from. Then you compare that with your current url using window.location.
If they are from the same domain, it means you are coming from your own site and you send them window.history.back(). If they are not the same, you are coming from somewhere else and you should redirect home or do whatever you like.