Outputting Google API Calls Inside Chrome Extension

Jack Robson

My aim is to output some of my Google Analytics data inside a new-tab page using a Chrome extension.

I've followed the "Hello Analytics API: JavaScript quickstart for web applications" found at https://developers.google.com/analytics/devguides/reporting/core/v3/quickstart/web-js#clientId as the basis for my new-tab page:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Hello Analytics - A quickstart guide for JavaScript</title>
</head>
<body>

<button id="auth-button" hidden>Authorize</button>

<h1>Hello Analytics</h1>

<textarea cols="80" rows="20" id="query-output"></textarea>

<script>

  // Replace with your client ID from the developer console.
  var CLIENT_ID = 'TAKEN OUT FOR SECURITY';

  // Set authorized scope.
  var SCOPES = ['https://www.googleapis.com/auth/analytics.readonly'];


  function authorize(event) {
    // Handles the authorization flow.
    // `immediate` should be false when invoked from the button click.
    var useImmdiate = event ? false : true;
    var authData = {
      client_id: CLIENT_ID,
      scope: SCOPES,
      immediate: useImmdiate
    };

    gapi.auth.authorize(authData, function(response) {
      var authButton = document.getElementById('auth-button');
      if (response.error) {
        authButton.hidden = false;
      }
      else {
        authButton.hidden = true;
        queryAccounts();
      }
    });
  }


function queryAccounts() {
  // Load the Google Analytics client library.
  gapi.client.load('analytics', 'v3').then(function() {

    // Get a list of all Google Analytics accounts for this user
    gapi.client.analytics.management.accounts.list().then(handleAccounts);
  });
}


function handleAccounts(response) {
  // Handles the response from the accounts list method.
  if (response.result.items && response.result.items.length) {
    // Get the first Google Analytics account.
    var firstAccountId = response.result.items[0].id;

    // Query for properties.
    queryProperties(firstAccountId);
  } else {
    console.log('No accounts found for this user.');
  }
}


function queryProperties(accountId) {
  // Get a list of all the properties for the account.
  gapi.client.analytics.management.webproperties.list(
      {'accountId': accountId})
    .then(handleProperties)
    .then(null, function(err) {
      // Log any errors.
      console.log(err);
  });
}


function handleProperties(response) {
  // Handles the response from the webproperties list method.
  if (response.result.items && response.result.items.length) {

    // Get the first Google Analytics account
    var firstAccountId = response.result.items[0].accountId;

    // Get the first property ID
    var firstPropertyId = response.result.items[0].id;

    // Query for Views (Profiles).
    queryProfiles(firstAccountId, firstPropertyId);
  } else {
    console.log('No properties found for this user.');
  }
}


function queryProfiles(accountId, propertyId) {
  // Get a list of all Views (Profiles) for the first property
  // of the first Account.
  gapi.client.analytics.management.profiles.list({
      'accountId': accountId,
      'webPropertyId': propertyId
  })
  .then(handleProfiles)
  .then(null, function(err) {
      // Log any errors.
      console.log(err);
  });
}


function handleProfiles(response) {
  // Handles the response from the profiles list method.
  if (response.result.items && response.result.items.length) {
    // Get the first View (Profile) ID.
    var firstProfileId = response.result.items[0].id;

    // Query the Core Reporting API.
    queryCoreReportingApi(firstProfileId);
  } else {
    console.log('No views (profiles) found for this user.');
  }
}


function queryCoreReportingApi(profileId) {
  // Query the Core Reporting API for the number sessions for
  // the past seven days.
  gapi.client.analytics.data.ga.get({
    'ids': 'ga:' + profileId,
    'start-date': '7daysAgo',
    'end-date': 'today',
    'metrics': 'ga:sessions'
  })
  .then(function(response) {
    var formattedJson = JSON.stringify(response.result, null, 2);
    document.getElementById('query-output').value = formattedJson;
  })
  .then(null, function(err) {
      // Log any errors.
      console.log(err);
  });
}

  // Add an event listener to the 'auth-button'.
  document.getElementById('auth-button').addEventListener('click', authorize);
</script>

<script src="https://apis.google.com/js/client.js?onload=authorize"></script>

</body>
</html>

I get the following errors:

  • Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' blob: filesystem: chrome-extension-resource:". Either the 'unsafe-inline' keyword, a hash ('sha256-ZJ1hGXIQLHmnXhFZqYWEDfv/ypJQ/Yvh6mYGne3Nf0s='), or a nonce ('nonce-...') is required to enable inline execution.
  • Refused to load the script 'https://apis.google.com/js/client.js?onload=authorize' because it violates the following Content Security Policy directive: "script-src 'self' blob: filesystem: chrome-extension-resource:".

Please advise.

Thanks, Jack

Haibara Ai

By default, inline script(Your first error) won't be executed, and only local script is loaded (Your second error).

To solve this, take a look at Content Security Policy, the recommendation would be extracting inline script to an external script (Your first error) and making a local copy of remote script (Your second error).

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Google Chrome - Extension vs App

From Dev

Google Chrome Extension Opening Url

From Dev

angularjs and google chrome extension

From Dev

Insert event with Google Calendar API in Chrome Extension keeps failing

From Dev

Authenticate Chrome extension with non-Google API using Google account

From Dev

Upload file inside chrome extension

From Dev

Chrome App inside an Extension

From Dev

Make calls to Drive API inside of a Google App Engine Cloud Endpoints

From Dev

Chrome Extension - Javascript Origins for Google API

From Dev

Why are my ajax calls synchronous in Chrome extension?

From Dev

Using Chrome auth to access gmail api inside of a Chrome Extension

From Dev

Developing Chrome Extension from inside the Chrome

From Dev

Chrome Extension Ajax Calls Returning 403

From Dev

Fetch API not sending session cookies when used inside a Chrome Extension

From Dev

Multiple web service calls from chrome extension

From Dev

Extension to Google Chrome browser that restarts Google Chrome

From Dev

Using google closure library inside chrome extension content script

From Dev

Fire extension on very page Google Chrome Extension

From Dev

Google Apps Script inside a Chrome Extension?

From Dev

angularjs and google chrome extension

From Dev

Upload file inside chrome extension

From Dev

Make calls to Drive API inside of a Google App Engine Cloud Endpoints

From Dev

Chrome Extension detect button inside extension

From Dev

Error with google chrome extension

From Dev

Google Chrome extension malware?

From Dev

Developing Chrome Extension from inside the Chrome

From Dev

Chrome Extension webRequest synchronous behavior for async calls

From Dev

Multiple web service calls from chrome extension

From Dev

Create a popup inside chrome extension

Related Related

  1. 1

    Google Chrome - Extension vs App

  2. 2

    Google Chrome Extension Opening Url

  3. 3

    angularjs and google chrome extension

  4. 4

    Insert event with Google Calendar API in Chrome Extension keeps failing

  5. 5

    Authenticate Chrome extension with non-Google API using Google account

  6. 6

    Upload file inside chrome extension

  7. 7

    Chrome App inside an Extension

  8. 8

    Make calls to Drive API inside of a Google App Engine Cloud Endpoints

  9. 9

    Chrome Extension - Javascript Origins for Google API

  10. 10

    Why are my ajax calls synchronous in Chrome extension?

  11. 11

    Using Chrome auth to access gmail api inside of a Chrome Extension

  12. 12

    Developing Chrome Extension from inside the Chrome

  13. 13

    Chrome Extension Ajax Calls Returning 403

  14. 14

    Fetch API not sending session cookies when used inside a Chrome Extension

  15. 15

    Multiple web service calls from chrome extension

  16. 16

    Extension to Google Chrome browser that restarts Google Chrome

  17. 17

    Using google closure library inside chrome extension content script

  18. 18

    Fire extension on very page Google Chrome Extension

  19. 19

    Google Apps Script inside a Chrome Extension?

  20. 20

    angularjs and google chrome extension

  21. 21

    Upload file inside chrome extension

  22. 22

    Make calls to Drive API inside of a Google App Engine Cloud Endpoints

  23. 23

    Chrome Extension detect button inside extension

  24. 24

    Error with google chrome extension

  25. 25

    Google Chrome extension malware?

  26. 26

    Developing Chrome Extension from inside the Chrome

  27. 27

    Chrome Extension webRequest synchronous behavior for async calls

  28. 28

    Multiple web service calls from chrome extension

  29. 29

    Create a popup inside chrome extension

HotTag

Archive