Search code examples
google-apps-scriptgoogle-analytics-api

Buld DV360 audience creation via API / ReferenceError: "Analytics" is not defined. (line 18, file "Code")


I am facing an issue ReferenceError: "Analytics" is not defined. (line 18, file "Code") while using the script from this article

My goal is to setup remarketing audiences in GA. Overall I have 14 accounts, but the list of audiences will remain the same.

Could you please help me to understand what went wrong?

function main() {

var settings = {'linkedView':"60000000",
              'linkedAccountId':"",
              'accountId':'',
              'propertyID':''};

 var spreadsheet = SpreadsheetApp.openByUrl('');
 var sheet = spreadsheet.getSheetByName('Sheet1');
 var range = sheet.getRange(1, 2, sheet.getLastRow(), 3);
 var values = range.getValues();
 Logger.log(values.length);

 for(var i = 0; i < values.length; i++) {
 var name = values[i][0];
 var categoryUrl = values[i][1];
 var duration = values[i][2];
 var newAudience = Analytics.Management.RemarketingAudience.insert(
  {
    'name': name,
    'linkedViews': [settings.linkedView],
    'linkedAdAccounts': [{
        'type': 'DBM_LINKS',
        'linkedAccountId': settings.linkedAccountId,
    }],
    'audienceType': 'SIMPLE',
    'audienceDefinition': {
      'includeConditions': {
        'daysToLookBack': 7,
        'segment': 'sessions::condition::ga:pagePath=@' + categoryUrl,
        'membershipDurationDays': duration,
        'isSmartList': false
      }
    }
  },
settings.accountId,
settings.propertyID);

Logger.log(i + ' Audience ' + name + ' has been created');
};
}

Solution

  • It looks like the Analytics object is not available. It needs to be enabled before you can use it.

    Here is a basic outline of how to do that:

    1. You need to enable the 'Google Analytics API' in the Advanced Google Services menu. [Menu Item[1] Popup

    2. Then you need to enable it in the 'Google Cloud Platform API Dashboard' using the link in the bottom of that second picture. Click '+ ENABLE APIS AND SERVICES' > search for 'Google Analytics API' and enable it!