How to show specific page views using google analytics api using html and javascript?

Viewed 48

Currently i am working in a project in which i require specific page views, users and sessions. I have configured out how to fetch it for the whole website using google analytics data api and now i am curious to know about how to do it for specific page. Below i am attaching my html and js code.

HTML CODE

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, shrink-to-fit=no"
    />
    <meta http-equiv="x-ua-compatible" content="ie=edge" />
    <title>Google Analtyics</title>
    
    <!-- Font Awesome -->
    <link
      rel="stylesheet"
      href="https://use.fontawesome.com/releases/v5.11.2/css/all.css"
    />
    <!-- Google Fonts Roboto -->
    <link
      rel="stylesheet"
      href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap"
    />
    <!-- MDB UI KIT -->
    <link rel="stylesheet" href="css/mdb.min.css" />
    <!-- Custom styles -->
    <style></style>
  </head>

  <body style="background-color: hsl(0, 0%, 96%)">
    <!--Main Navigation-->
    <header class="mb-10">
      <!-- Navbar-->
      <nav
        class="navbar navbar-expand-lg navbar-light bg-white shadow-2 fixed-top"
      >
        <div
          class="
            container-fluid
            justify-content-center justify-content-md-between
          "
        >

          <!-- Right elements -->
          <ul class="navbar-nav flex-row d-none d-md-flex">
            <li class="nav-item me-3 me-lg-1">
              <button
                id="sign-in-btn"
                type="button"
                class="btn btn-primary btn-rounded"
                style="display: none"
                onclick="signIn()"
              >
                Login
              </button>
            </li>

            <li class="nav-item me-3 me-lg-1">
              <button
                id="sign-out-btn"
                type="button"
                class="btn btn-primary btn-rounded"
                style="display: none"
                onclick="signOut()"
              >
                Logout
              </button>
            </li>

            <li class="nav-item me-3 me-lg-1">
              <button
                type="button"
                class="btn btn-primary btn-rounded"
                style="display: none"
                onclick="loadData()"
              >
                Load Data
              </button>
            </li>

            
          </ul>
          <!-- Right elements -->
        </div>
      </nav>
      <!-- Navbar -->
    </header>
    <!--Main Navigation-->

    <!--Main layout-->
    <main>
      <div class="container">
        <!--Section: Design Block-->
        <section class="mb-8">
          <h3 class="mb-7 text-center fw-bold">Last 7 days</h3>
          <div class="row">
            <div class="col-md-4 mb-4 mb-md-0">
              <!-- Card -->
              <div class="card">
                <div
                  class="
                    card-body
                    d-flex
                    justify-content-start
                    align-items-center
                  "
                >
                  <div
                    class="
                      bg-primary
                      text-white
                      rounded-4
                      d-flex
                      justify-content-center
                      align-items-center
                    "
                    style="width: 50px; height: 50px"
                  >
                    <i class="fas fa-users fa-lg"></i>
                  </div>
                  <div class="ms-3">
                    <p class="text-muted mb-1">Users</p>
                    <p class="mb-0">
                      <span id="displayUsers" class="h4 me-2"></span>
                    </p>
                  </div>
                </div>
              </div>
              <!-- Card -->
            </div>
            <div class="col-md-4 mb-4 mb-md-0">
              <!-- Card -->
              <div class="card">
                <div
                  class="
                    card-body
                    d-flex
                    justify-content-start
                    align-items-center
                  "
                >
                  <div
                    class="
                      bg-primary
                      text-white
                      rounded-4
                      d-flex
                      justify-content-center
                      align-items-center
                    "
                    style="width: 50px; height: 50px"
                  >
                    <i class="fas fa-file fa-lg"></i>
                  </div>
                  <div class="ms-3">
                    <p class="text-muted mb-1">Page views</p>
                    <p class="mb-0">
                      <span id="displayPageViews" class="h4 me-2"></span>
                    </p>
                  </div>
                </div>
              </div>
              <!-- Card -->
            </div>
            <div class="col-md-4">
              <!-- Card -->
              <div class="card">
                <div
                  class="
                    card-body
                    d-flex
                    justify-content-start
                    align-items-center
                  "
                >
                  <div
                    class="
                      bg-primary
                      text-white
                      rounded-4
                      d-flex
                      justify-content-center
                      align-items-center
                    "
                    style="width: 50px; height: 50px"
                  >
                    <i class="fas fa-chart-line fa-lg"></i>
                  </div>
                  <div class="ms-3">
                    <p class="text-muted mb-1">Sessions</p>
                    <p class="mb-0">
                      <span id="displaySessions" class="h4 me-2"></span>
                    </p>
                  </div>
                </div>
              </div>
              <!-- Card -->
            </div>
          </div>
        </section>
        <!--Section: Design Block-->
      </div>
    </main>
    <!--Main layout-->

    <!--Footer-->
    <footer></footer>
    <!--Footer-->
  </body>

  <!-- MDB ESSENTIAL -->
  <script type="text/javascript" src="js/mdb.min.js"></script>
  <!-- Google API -->
  <script src="https://apis.google.com/js/api.js"></script>
  <!-- easyData - Google Analtyics -->
  <script type="text/javascript" src="js/easyData-google-analtyics.js"></script>

  <!--Fetching data-->
  <script>
    // Your Client ID
    const CLIENT_ID = "";

    function loadData() {
      // Your GA property ID
      const propertyId = "";

      const startDate = "7daysAgo";
      const endDate = "today";
      const metrics = [
        { name: "activeUsers" },
        { name: "screenPageViews" },
        { name: "sessions" },
      ];

      const query = {
        dateRanges: [{ startDate, endDate }],
        metrics: metrics,
      };

      runReport(propertyId, query, displayResult);
    }

    function displayResult(response) {
      document.getElementById("displayUsers").innerHTML =
        response.result.rows[0].metricValues[0].value;
      document.getElementById("displayPageViews").innerHTML =
        response.result.rows[0].metricValues[1].value;
      document.getElementById("displaySessions").innerHTML =
        response.result.rows[0].metricValues[2].value;
    }

    // Login buttons
    document.addEventListener("gapi-loaded", (e) => {
      if (isSignedIn()) {
        document.getElementById("sign-out-btn").style.display = "block";
        document.getElementById("sign-in-btn").style.display = "none";
        loadData();
      } else {
        document.getElementById("sign-in-btn").style.display = "block";
        document.getElementById("sign-out-btn").style.display = "none";
      }
    });
  </script>
</html>

JAVASCRIPT CODE

// Google Analytics

const GA_SCOPE = "https://www.googleapis.com/auth/analytics.readonly";
const GA_API_URL = "https://analyticsdata.googleapis.com/$discovery/rest?version=v1beta";

gapi.load("client:auth2", function () {
  gapi.auth2.init({ client_id: CLIENT_ID }).then(() => document.dispatchEvent(new Event('gapi-loaded')));
});

function signIn(scope = GA_SCOPE) {
  return gapi.auth2.getAuthInstance().signIn({ scope }).then(() => {
    setCookie('guser-loggedin', 'true', 1);
    location.reload();
  }, (e) => console.error(e));
}

function signOut() {
  return gapi.auth2.getAuthInstance().signOut().then(() => {
    setCookie('guser-loggedin', 'true', -1);
    location.reload();}, (e) => console.error(e));
}

function loadClient(apiPath = GA_API_URL) {
  return gapi.client.load(apiPath);
}

function runReport(propertyId, query, cb = function (res) { console.log(res); }, err = function (err) { console.error(err); }) {

  return loadClient().then(() => gapi.client.analyticsdata.properties
    .runReport({
      property: "properties/" + propertyId,
      resource: query
    })
    .then(cb, err));
}

function isSignedIn() {
  if (getCookie('guser-loggedin') === 'true') return true;
  return false;
}

function setCookie(cname = 'guser-loggedin', cvalue, exdays) {
  const d = new Date();
  d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
  let expires = "expires="+d.toUTCString();
  document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

function getCookie(cname) {
  let name = cname + "=";
  let ca = document.cookie.split(';');
  for(let i = 0; i < ca.length; i++) {
    let c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}
0 Answers
Related