Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 540
Arman Bagheri Avatar asked Dec 06 '25 04:12

Arman Bagheri


2 Answers

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.

like image 91
Master DJon Avatar answered Dec 08 '25 16:12

Master DJon


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";
    }
});
like image 38
Arman Bagheri Avatar answered Dec 08 '25 18:12

Arman Bagheri