Webflow sync, pageviews & more.
NEW
Answers

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?

To implement a back button with a condition in Webflow using JavaScript, you can take advantage of the browser's `document.referrer` property. This property returns the URL of the page that linked to the current page.

Here's a step-by-step guide on how you can achieve this:

1. Add a button element to your Webflow page where you want the back button to appear.

2. Give the button a class name or an ID that you can reference in your JavaScript code. For example, you can assign it the class "back-button".

3. In the Webflow Designer, go to the page settings and give your page a unique class name or ID. For example, you can add the class "custom-page" to the body element.

4. Open the Custom Code section of your Webflow project settings and navigate to the Footer section. This is where you can add your custom JavaScript code.

5. Add the following JavaScript code:

```javascript
// Find the back button element
const backButton = document.querySelector('.back-button');

// Add a click event listener to the back button
backButton.addEventListener('click', () => {
// Check if the referrer URL is from the same domain
if (
document.referrer.includes(window.location.hostname)
) {
// If the referrer URL is from the same domain, go back to the previous page
window.history.back();
} else {
// If the referrer URL is from a different domain, redirect to a default page
window.location.href = 'https://example.com/default-page';
}
});
```

6. Customize the `https://example.com/default-page` URL to the desired default page you want to redirect users to when they come from a different domain.

By following these steps, the back button will now check if the user came from the same domain or a different domain by comparing the referrer URL. If they came from the same domain, it will take them back to the previous page using `window.history.back()`. If they came from a different domain, it will redirect them to the default page specified.

Remember to publish your Webflow project for the changes to take effect.

Rate this answer

Other Webflow Questions