Javascript: How to replace part of the a link with the current URL?

Hi there, I’ve got a link that exists on many pages, which I would like to use JavaScript to make the later part of the link to be changed according to the current url* of the visiting page.

(*current url mentioned here = the current web address appears on the browser’s address bar)

What is the right way to change URL after ?redirect= to the current visiting URL using JavaScript?

For example, this is the original:

<a href="https://app.example.com/?redirect=www.example.com">Link</a>

Now, the current url is https://www.example.com/game?q=123, the desired result would be:

<a href="https://app.example.com/?redirect=https://www.example.com/game?q=123">Link</a>

Thanks a lot :pray:

I’d recommend jQuery, for its ease of use.

I’ll reference my webflow-utils library which has some examples of the type of code you’ll need to perform these tasks.

The approach you take will depend a lot on how many links you need to modify, how easy they are to identify in your page, whether they may have other querystring key/value parts, and so on.

However, there are three basic steps to what you’re wanting to do;

  1. Identify which links you want to modify, perhaps by an ID, or a class, or a custom attribute. Perhaps even something unique in the URL href itself. Make your links identifiable in some way, so that your script knows which ones to modify, and which to leave untouched.

  2. In a jQuery event on page load, you’ll select your desired elements. Before /body…

$(function () {
// your code here
});
  1. For each element you match, change the href as you like.

You can find some example code for both the element selection and the href modification steps here;

Thanks @memetican for your reply. It looks difficult to me :sweat_smile:


Here is the script tried so far. It works but still has a problem.

document.addEventListener("DOMContentLoaded", function (e) {
  document.querySelectorAll("a").forEach(function (element) {
    const url_str = element.getAttribute("href");
    const this_url = new URL(url_str);
    if (this_url.searchParams.get("redirect")) {
      const current_url = window.location.href;
      const redirect = this_url.searchParams.set("redirect", current_url);
      element.setAttribute("href", this_url.href);
    }
  });
})

Problem 1: How to remove https:// and http://?

eg. If the current address is https://www.example.com/about/dog

Desired result: https://app.example.com/?redirect=www.example.com/about/dog
Not desired: https://app.example.com/?redirect=https://www.example.com/about/dog

Problem 2: Not idea what is conflicting… The script is not working on all pages.
I am not sure but it looks like .addEventListener is not working on some pages.
I guess the above script may not be the best approach.

Trying this on CodePen: https://codepen.io/pen/mdxZJGx

Nice work! I’ve forked your pen and made some mods, try this;

I’m on a Codepen pro account, so for testing, you can comment out your script, and then paste this into your page’s code before </body>.

<script src="https://codepen.io/memetican/pen/BargWvZ/eecc8cfd1f2a5d371ad9d5210660f3e4.js"></script>

Key changes;

  • I’m using jQuery, it just as a neater syntax, and Webflow already includes the jQuery library.
  • Replaced event listener with jQuery’s on DOM loaded syntax, hopefully that will resolve your conflict.
  • Restricted the select of <a> elems to those having an href that contains the text redirect. This just focuses in on the most likely elements needing transformation.
  • Pretty much everything else left as is, nice work
  • Added support for your protocol removal. Since we know any legit correctly-encoded URL will have one and only one :// we can just split on that and grab the second half.

Note that using the URL object will correctly URL-encode your strings, so in your desired example of;

https://app.example.com/?redirect=www.example.com/about/dog

You’d actually get a more correct;

https://app.example.com/?redirect=www.example.com%2Fabout%2Fdog

Also in your current design, if your current page URL has a querystring, it will be included too in the href. I’m assuming that’s what you’re after, but pointing it out just in case.

Querystrings are uncommon in Webflow sites, however you might see them if e.g. you have a Google Ad pointing to your page and Google appends a ?gclid= to your URL. Querystrings may also be used in Webflow paginated Collection Lists, and perhaps secure page logins… I can’t recall how those are setup.

And a totally interesting subpoint. If you run your script on a page inside of an IFRAME, then window.location.href picks up the IFRAME’s URL and not the parent page- which is what you see in the URL bar. In the rendered Codepen widget, you can see the URL’s picked Codepen’s URL, rather than the one from discourse.webflow.com

1 Like

@memetican thanks so much!
Thanks for the nice codes and super detailed explanation! Learn a lot!

I added this to remove the last slash from the url:

// Remove the last slash
let regex = /\/$/;
let clean_url = current_url.replace(regex, "");

Is there a way to keep the query string un-encoded,
which means:
?redirect= www.example.com/about/dog
instead of ?redirect= www.example.com%2Fabout%2Fdog

I tried to use this but was not successful:
decodeURI() - JavaScript | MDN

Glad it helped!

So normally, you would always want the URL encoded into its param, so that your URL is legal. For example, if your current page URL was…

http://www.mysite.com/?gclid=12345

And you embed that unencoded into a URL querystring parameter, you might get;

http://www.newsite.com/?redirect=www.mysite.com/?gclid=12345

Depending on the browser and HTTP server trying to process it, I don’t know what the result of having multiple querystrings would be.

The server that’s receiving it automatically decodes the param, so you really do want to preserve that integrity.

That said if there was a reason you wanted to avoid that, and create URLs that weren’t technically legit, you can do that with a standard string concatenation, or using a regex replace.

Here’s a crude example that first creates the querystring param with a magic string, using the javascript URL object. XXXX doesn’t require any encoding so it would remain intact. Then you’d use a standard string replace to replace that with your un-encoded URL.

const redirect = this_url.searchParams.set("redirect", 'XXXX');
this_url.href.replace ('XXXX', current_url);

You could use a more complex magic string, to minimize the risk of accidentally matching something else in the URL.

1 Like

Thanks!

Finally solved with decodeURIComponent

$(this).attr("href", decodeURIComponent(this_url.href));

1 Like