'Can I even connect client-side JavaScript to google-analytics API?

I have been researching the google analytics api (GA4) for the past day. And I want to be able to use GA4 api functions like runReport on the client-side. There is a piece of analytics that I want each of my web-clients to see.

Here is the code that I pulled out from the gapi documentation.

<script src="https://apis.google.com/js/api.js"></script>
<script>
  /**
   * Sample JavaScript code for analyticsdata.properties.runReport
   * See instructions for running APIs Explorer code samples locally:
   * https://developers.google.com/explorer-help/code-samples#javascript
   */

  function authenticate() {
    return gapi.auth2.getAuthInstance()
        .signIn({scope: "https://www.googleapis.com/auth/analytics https://www.googleapis.com/auth/analytics.readonly"})
        .then(function() { console.log("Sign-in successful"); },
              function(err) { console.error("Error signing in", err); });
  }
  function loadClient() {
    gapi.client.setApiKey("FILLED_THIS_WITH_MY_API_KEY");
    return gapi.client.load("https://analyticsdata.googleapis.com/$discovery/rest?version=v1beta")
        .then(function() { console.log("GAPI client loaded for API"); },
              function(err) { console.error("Error loading GAPI client for API", err); });
  }
  // Make sure the client is loaded and sign-in is complete before calling this method.
  function execute() {
    return gapi.client.analyticsdata.properties.runReport({
      "resource": {}
    })
        .then(function(response) {
                // Handle the results here (response.result has the parsed body).
                console.log("Response", response);
              },
              function(err) { console.error("Execute error", err); });
  }
  gapi.load("client:auth2", function() {
    gapi.auth2.init({client_id: "FILLED_THIS_WITH_MY_CLIENT_ID"});
  });
</script>
<button onclick="authenticate().then(loadClient)">authorize and load</button>
<button onclick="execute()">execute</button>

And it gives me this error:

gapi.auth2.ExternallyVisibleError: Invalid cookiePolicy\


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source