Webflow sync, pageviews & more.
NEW

What is the correct way to use JavaScript to dynamically change the URL after "?redirect=" to match the current visiting URL in Webflow?

TL;DR
  • Use JavaScript to get the current page URL with window.location.href.
  • Target links with a custom attribute like data-redirect-link and update or append the ?redirect= parameter using JavaScript on page load.

To dynamically change the value of ?redirect= in a URL on a Webflow site using JavaScript, you'll need to detect the current page URL and then update relevant links on the page.

1. Define the Goal

Your aim is to dynamically replace or update the ?redirect= parameter in certain links to reflect the current page URL.

2. Get the Current Page URL

  • Use JavaScript’s window.location.href to get the full URL of the current page.
  • Example: If you're visiting https://yourwebsite.com/page, this will return that full string.
  • Use JavaScript to find links with a ?redirect= parameter and update the parameter value.
  • Target the relevant elements using classes, custom attributes, or specific container IDs.

4. Sample Approach

Here’s how to do it using standard JS (add this in Page Settings → Before tag within Webflow):

  • Identify all links on the page (or narrow it with .querySelectorAll("[data-redirect-link]") using a custom attribute like data-redirect-link).
  • Replace existing ?redirect= values or append it if it doesn't exist.

Example:

document.addEventListener("DOMContentLoaded", function () {  const currentUrl = window.location.href;  const links = document.querySelectorAll("a[data-redirect-link]"); // Add this custom attribute to your target links  links.forEach(link => {    const baseUrl = link.href.split("?redirect=")[0];    link.href = `${baseUrl}?redirect=${encodeURIComponent(currentUrl)}`;  });});

5. Setup in Webflow

  • Assign data-redirect-link as a custom attribute to any link that should have this behavior.
  • Paste the script in the page’s custom code area (under Settings → Before ).

Summary

To dynamically inject the current page URL into ?redirect= parameters in Webflow:

  • Use window.location.href to get the active URL.
  • Use JavaScript to target links with a custom attribute like data-redirect-link.
  • Replace or append the ?redirect= parameter accordingly during page load.
Rate this answer

Other Webflow Questions