简体   繁体   中英

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>

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. ie Home->Product->Home. I'll let you search for further code that would let you counter this problem.

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";
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM