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 JavaScript to the page's "Custom Code" section by inserting the provided snippet with your back button's ID and default URL.
  • Ensure the button element in Webflow has the correct ID.
  • Publish and test the site to confirm the back button functions based on the referrer domain.

To implement a back button in Webflow that considers the referrer domain, use JavaScript to check the previous page's domain and navigate accordingly.

1. Add JavaScript to Your Page

  • Open the Page Settings of the page containing the button.
  • Scroll to the "Custom Code" section and locate the "Before </body> tag" area.

2. Insert the JavaScript Code

  • Add the following JavaScript snippet:

  ```javascript

  <script>

  document.addEventListener('DOMContentLoaded', function() {

      var backButton = document.getElementById('back-button-id');

      var defaultPage = '/default-page-url'; // Change this to your default page URL

      backButton.addEventListener('click', function() {

          var referrer = document.referrer;

          if (referrer && new URL(referrer).hostname === window.location.hostname) {

              window.history.back();

          } else {

              window.location.href = defaultPage;

          }

      });

  });

  </script>

  ```

  • Replace back-button-id with the ID of your back button element.
  • Replace /default-page-url with the URL of your default fallback page.

3. Set Up the Button Element

  • Go to the Webflow designer and find the back button element.
  • Ensure the back button has the correct ID that matches the ID you used in the JavaScript.

4. Publish and Test

  • Publish your Webflow site to test the functionality.
  • Click the back button to verify it navigates appropriately based on the referrer domain.

Summary

This solution uses JavaScript to check the referring page's domain. If the referrer is from the same domain, it navigates back; otherwise, it redirects to a predefined default page. Make sure the button ID and default page URL are correctly set in your JavaScript snippet.

Rate this answer

Other Webflow Questions