๐คท What does it do?
This custom JavaScript variable extracts information about the referrer URL. This includes details such as the full referrer URL, the protocol, hostname, port, pathname, and query parameters.
๐งโ๐ป Usecase
Referrer information can be used to understand where your website traffic is coming from. This information can inform your marketing and SEO strategy. For instance, if you notice a high volume of traffic from a specific website, you might want to investigate why that site is sending so much traffic your way, or consider partnering with them for future promotions.
๐ Instructions
You can retrieve this information directly from the document
object provided by the browser. No need to manipulate session storage or local storage. Here’s an example of a GTM Custom JavaScript variable that returns an object with detailed referrer information:
function() {
var parser = document.createElement('a');
parser.href = document.referrer;
return {
href: parser.href,
protocol: parser.protocol,
hostname: parser.hostname,
port: parser.port,
pathname: parser.pathname,
search: parser.search,
hash: parser.hash
};
}
This JavaScript function uses an HTMLAnchorElement (<a>
) to parse the referrer URL, and returns an object containing various parts of the URL. The referrer URL is accessed via document.referrer
.
Here’s what each property in the returned object represents:
href
: the entire URL.protocol
: the web protocol used (e.g., http: or https:).hostname
: the domain name of the website (e.g., www.example.com).port
: the port number used, if any (e.g., 80 or 443). If no port number is used, this will be an empty string.pathname
: the path section of the URL, that comes after the hostname and before the query, including the initial slash if present.search
: the query parameters of the URL, including the leading question mark.hash
: the fragment identifier of the URL, including the leading hash mark.
Remember, you can also use GTM’s built-in Referrer variable, but the Custom JavaScript variable provides more granular information.
Isn’t this the macro you were looking for? Check-out all the macro’s which I’ve shared on my site or request one.