Webflow sync, pageviews & more.
NEW

How can I implement a back button with a condition in Webflow using JavaScript, where the button takes the user back to the previous page if they came from the same domain, and if they came from a different domain, it takes them to a default page?

TL;DR
  • Add a uniquely identified button in Webflow.
  • Use JavaScript to check if the referrer is from the same domain; if true, navigate back, else redirect to a fallback page.

To implement a back button with conditional behavior in Webflow using JavaScript, you’ll check the user's referrer and decide whether to go back or redirect.

1. Add a Custom Button to Your Webflow Page

  • Add a Button element to your Webflow project.
  • Give it a unique ID or class (e.g., back-button) to target it with JavaScript.
  • Go to Page Settings or use an Embed element with Before tag placement.
  • Insert the following JavaScript (no raw HTML tags, safe to use inline descriptions):
<script>  document.addEventListener("DOMContentLoaded", function () {    const sameDomain = location.hostname;    const referrerDomain = document.referrer ? new URL(document.referrer).hostname : null;    const backBtn = document.getElementById('back-button'); // Adjust to your button's ID    if (backBtn) {      backBtn.addEventListener('click', function (e) {        e.preventDefault();        if (referrerDomain && referrerDomain === sameDomain) {          window.history.back();        } else {          window.location.href = "/default-page"; // Update with your fallback URL        }      });    }  });</script>

3. Customize as Needed

  • Replace /default-page with the actual path to your fallback page.
  • Ensure the button you're targeting has the exact same ID or class as referenced in the script (back-button).
  • You can also hide or disable the button conditionally if no document.referrer is available.

Summary

To create a conditional back button in Webflow, use JavaScript to check if document.referrer matches your domain. If so, go back in history; otherwise, redirect to a default page. This ensures users return consistently whether they came from internal or external pages.

Rate this answer

Other Webflow Questions