I am trying to create a back button using JS with a condition in case the user comes from any domain other than my website.
To put this in context:
User browses from category to CMS item, the back button will send the user to category.
the user browses from home page to the same CMS item, the back button will send the user to home page
Condition is to set a default page for the back button if the user comes from any other domain (for example from Google to CMS item, the user is sent to home page).
I’ve found the follow code:
function backClick() {
if (document.referrer.indexOf(window.location.host) !== -1) {
history.go(-1); return false;
}
else { window.location.href = 'https://mydomain.com'; }
}
I’ve placed both the code to rename the onclick attribute (according to forum post) together with the function backClick in the body of the page, but no luck.
Can anyone guide me to where/how to implement this code?
Thank you for the answers and sorry for not replying. This has been on the back burner for a while. I’ve managed to make it work by doing the following;
Turn goBack attribute to onClick event (since Webflow doesn’t allow it) using the following code in the head of the page:
<script>
window.onload = function() {
var anchors = document.getElementsByTagName('*');
for(var i = 0; i < anchors.length; i++) {
var anchor = anchors[i];
anchor.onclick = function() {
code = this.getAttribute('goBack');
eval(code);
}
}
}
</script>
<script>
function backClick() {
if(document.referrer.indexOf('yourdomain.com') >= 0) {
history.go(-1);
}
else {
window.location.href = '/'; // this might just be '/' of your site
}
return false;
}
</script>
This will create a browser back button, unless the user was not on your domain and will then be redirected to the home page.