Reputation: 429
I am using this code for generating a "Go back" link in my website
<script>
document.write('<button onclick="location.href=\'' + document.referrer + '\';">Go back</button>');
</script>
But when the user lands directly on this page (foe example after google search), the "go back" button doesn't work.
How can I do it in such a cases to go to mypage.html?
Thank you
Upvotes: 0
Views: 2064
Reputation: 414
You can also check if the referrer is empty with an if statement like this:
if (document.referrer != ""){
document.write('<button onclick="location.href=\'' + document.referrer + '\';">Go back</button>');
}
else{
document.write('<button onclick="location.href=\'mypage.html\'">Go back</button>');
}
Then you go to mypage.html and that doesn't happen with javascript:history.go(-1)
Upvotes: 2
Reputation: 10588
You can use the JavaScript history API: javascript:history.go(-1)
.
Upvotes: 0