Sybrentjuh
Sybrentjuh

Reputation: 287

How to check if Referrer URL has URL parameters?

I'd like to check if my Referrer URL has parameters in it. Because based on this I'd like to change the url of a button to a different page.

What I have now:

var referrer = document.referrer;
var referrerparams = referrer.search;

if (referrerparams) {
 > 'script to change urlbutton.href'
}

So I thought i could use both document.referrer and window.location.search, to see if the referrer URL has parameters in it. Independently these two work fine, but not together. I get the following in console: ƒ search() { [native code] }.

Does anyoneone know how to check if the Referrer URL has parameters? It doesn't even matter what parameters, just if they exit.

Upvotes: 0

Views: 2826

Answers (1)

Lionel Rowe
Lionel Rowe

Reputation: 5926

You can create a URL object from the referrer and check its search property.

const referrerQueryParamStr = new URL(document.referrer).search

if (referrerQueryParamStr) {
    // change urlbutton.href
}

If you want the individual key-value pairs in an easy-to-use format, you can use the searchParams property instead:

const referrerQueryParams = new URL(document.referrer).searchParams

for (const [key, val] of referrerQueryParams) {
    console.log({ key, val })
}

I get the following in console: ƒ search() { [native code] }.

This is because document.referrer is just a string before you convert it. What you're logging is actually the String#search function.

typeof document.referrer // string
typeof document.referrer.search // function
document.referrer.search === String.prototype.search // true

Upvotes: 1

Related Questions