Bocho Todorov
Bocho Todorov

Reputation: 429

If "Back" link with document.referrer is empty go to certain URL

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

Answers (2)

Dinizworld
Dinizworld

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

Erik A. Brandstadmoen
Erik A. Brandstadmoen

Reputation: 10588

You can use the JavaScript history API: javascript:history.go(-1).

Upvotes: 0

Related Questions