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
  • Add JavaScript in Webflow’s Footer or Embed element to run after the page loads.
  • Use JavaScript to get the current URL and update ?redirect= in link hrefs with data-redirect="true" or in the browser address bar without reloading the page.

To dynamically update the URL parameter after ?redirect= to reflect the current page URL in Webflow, you’ll need to use JavaScript at runtime in the browser.

1. Insert Custom Code in Webflow

  • Go to Project Settings > Custom Code > Footer or use an Embed element in your Webflow page.
  • Ensure the script is placed after the page content loads (e.g., inside the Footer section or using DOMContentLoaded).

2. Write JavaScript to Update the Redirect Parameter

  • Use the following logic:

  • Get the current page URL.

  • Update or add the ?redirect= parameter in links or in the browser’s address bar.

  • Example script to update a link with ?redirect=currentUrl:

<script>  document.addEventListener("DOMContentLoaded", function () {    const links = document.querySelectorAll('a[data-redirect="true"]');    const currentUrl = window.location.href;    links.forEach(link => {      const baseHref = link.href.split('?')[0];      link.href = `${baseHref}?redirect=${encodeURIComponent(currentUrl)}`;    });  });</script>
  • Add data-redirect="true" to any link you want to dynamically set.

3. Update the Browser URL (If Needed)

  • To replace or add the redirect= parameter in the current page URL without reloading:
<script>  document.addEventListener("DOMContentLoaded", function () {    const url = new URL(window.location);    url.searchParams.set('redirect', window.location.href);    window.history.replaceState({}, '', url);  });</script>
  • This updates the browser bar with the redirect=currentPage parameter without refreshing the page.

Summary

To dynamically set ?redirect= to the current URL in Webflow, add JavaScript in an embed or the footer section. Use window.location.href to get the current URL, and then update either link destinations or the browser address bar using JavaScript and URL object methods.

Rate this answer

Other Webflow Questions