Learn business growth with Google Analytics 4 Forums Google Analytics 4 How to include website domain in GA4 Google Analytics?

  • How to include website domain in GA4 Google Analytics?

    Posted by John on 19 January 2023 at 11:27 pm

    You know, I’ve been using this bit of code to append variables to each page for Google Analytics tracking:

    function pageViewGa(pagePath, pageUrl, host) {
        gtag("event", "page_view", {
            "page_title": pagePath,
            "page_location": pageUrl,
            "page_path": pagePath
        });
    }
    

    It’s been working well for the most part, but there’s something I’d like to add. I can’t seem to figure out how to get the hostname to show up on Google Analytics. You wouldn’t happen to know how I can do that, would you? Here’s a screenshot for reference:
    Google Analytics screenshot

    Owen replied 10 months, 3 weeks ago 3 Members · 2 Replies
  • 2 Replies
  • Charlotte

    Member
    2 February 2023 at 4:47 pm

    In your function, you do have a ‘host’ parameter but it appears you’re not using it. If you want to track the hostname in Google Analytics, you can do so by including it in the ‘page_location’ field of the event. This field is meant to track the full URL including the domain ( hostname ). You can combine the host and the page path like this – host + pagePath, which gives you the full URL. Your code would look like this:

    
    function pageViewGa(pagePath, pageUrl, host) {
        gtag("event", "page_view", {
            "page_title": pagePath,
            "page_location": host + pagePath,
            "page_path": pagePath
        });
    }
    

    This way, you will be tracking the hostname on Google Analytics.

  • Owen

    Member
    28 February 2023 at 10:43 pm

    You’re on the right track. It seems like you already have the “host” as a parameter in your function, but you’re not using it in the properties that you’re setting for the gtag pageview event. To track the hostname, you can simply append the hostname to the “page_path” and “page_location” properties.

    For “page_location”, ideally, it should contain the complete URL such that it includes the protocol (http or https), hostname and path.

    For “page_path”, it encompasses the page’s path and other information that comes after the domain name in the URL, you can add the hostname too for your reference.

    Here’s how to do it:

    `javascript
    function pageViewGa(pagePath, pageUrl, host) {
    gtag(“event”, “page_view”, {
    “page_title”: pagePath,
    “page_location”: host + pageUrl,
    “page_path”: host + pagePath
    });
    }
    `
    Just replace “pageUrl” and “pagePath” with your “host + pageUrl” and “host + pagePath” respectively, this will contain your hostname.
    Remember to make sure that “host” contains the correct value. If it doesn’t, you can get it from “window.location.hostname” in JavaScript.

Log in to reply.