Track referrer url despite redirect

127 Views Asked by At

In my web application, when the website loads we convert query parameters to hash routes - so the router can use them.

var url = "https://www.example.com/home?page=admin";
var urlObj = new URL(url);

var pageParam = urlObj.searchParams.get("page");

if (pageParam) {
   window.open(window.location.origin + "/home/#/" + pageParam);
}

The issue is that when this redirect happens, the Referrer is overridden. So in this case the Referrer becomes the current origin,

https://www.google.com/
--> https://www.example.com/home?page=admin
--> https://www.example.com/home/#/admin
    (Referrer: https://www.example.com/home?page=admin)

I need to retain the original Referrer to be captured in Analytics.

Is there any way to update the URL while still maintaining the original Referrer URL?

1

There are 1 best solutions below

0
Adnan Arif Sait On BEST ANSWER

I used the History.replaceState() method to update the URL without refreshing the page. Since the origin remains the same, replaceState can be used.

var url = "https://www.example.com/home?page=admin";
var urlObj = new URL(url);

var pageParam = urlObj.searchParams.get("page");

if (pageParam) {
  window.history.replaceState(
    null,
    "",
    window.location.origin + "/home/#/" + pageParam
  );
}

With this the page does not redirect, so the referrer remains the same.

https://www.google.com/
--> https://www.example.com/home?page=admin
--> (replaceState) https://www.example.com/home/#/admin
    (Referrer: https://www.google.com/)