Arman Bagheri
Arman Bagheri

Reputation: 630

Define a reference site for the history.back button

We want to have a back button in our site but history.back in javascript does not help us. We need this function only run on the site and if the user comes from other site, clicking the return button on the previous site should not return.

In fact, we want a return button to run on our site only. my code is

<a href="javascript:history.back();" class="btn btn-danger btn-rounded btn-anim"><i class="fas fa-arrow-left"></i><span class="btn-text">Back</span></a>

Upvotes: 2

Views: 558

Answers (2)

Arman Bagheri
Arman Bagheri

Reputation: 630

This code checks the history of back button of the browser on its click event:

$('#backbtn').click(function () {
    if (document.referrer.includes(window.location.hostname)) {
        window.history.back();
    } else {
        window.location.href = "/your/path";
    }
});

Upvotes: 4

Master DJon
Master DJon

Reputation: 1965

This only works for your own made back button and won't work with the browser back button

There is two ways to achieve that: a simple but not always reliable method and a complex one but always good.

1- The simple method

You use document.referrer and ensure the domain is yours before calling history.back().

2- The complex method

You could register a JavaScript function on page load to get the first URL the internaut land which you could store using history.pushState. Before calling the back function, you could ensure this is not that page. Though, this idea is not complete as the user could probably have landed on this page twice. i.e. Home->Product->Home. I'll let you search for further code that would let you counter this problem.

Upvotes: 5

Related Questions