Skip to content

Instantly share code, notes, and snippets.

@abfo
Created February 13, 2023 01:16
Show Gist options
  • Save abfo/c4b6df6d2a1997c3e277f337e47999a6 to your computer and use it in GitHub Desktop.
Save abfo/c4b6df6d2a1997c3e277f337e47999a6 to your computer and use it in GitHub Desktop.
Google Apps Script code to send you an email every time a Google Analytics 4 property has a new referrer. Full instructions at https://ithoughthecamewithyou.com/post/email-alerts-for-new-referers-in-google-analytics-using-apps-script
var PropertyId = '';
var PropertyName = ''
var SendEmailTo = '';
function main() {
var scriptProperties = PropertiesService.getScriptProperties();
var currentProps = scriptProperties.getProperties();
var anythingNew = false;
var newText = '';
const metric = AnalyticsData.newMetric();
metric.name = 'totalUsers';
const dimension = AnalyticsData.newDimension();
dimension.name = 'pageReferrer';
const dateRange = AnalyticsData.newDateRange();
dateRange.startDate = 'yesterday';
dateRange.endDate = 'yesterday';
const dimensionfilter = AnalyticsData.newFilterExpression()
dimensionfilter.filter = AnalyticsData.newFilter()
dimensionfilter.filter.fieldName = 'sessionMedium'
dimensionfilter.filter.stringFilter = AnalyticsData.newStringFilter()
dimensionfilter.filter.stringFilter.value = 'referral'
const request = AnalyticsData.newRunReportRequest();
request.dimensions = [dimension];
request.metrics = [metric];
request.dateRanges = dateRange;
request.dimensionFilter = dimensionfilter;
const report = AnalyticsData.Properties.runReport(request,
'properties/' + PropertyId);
if (!report.rows) {
Logger.log('GA returned no data.');
return;
}
for (var i = 0; i < report.rowCount; i++){
var referrer = report.rows[i].dimensionValues[0].value;
if ((referrer) && (referrer.length > 0)) {
if (!(referrer in currentProps)){
Logger.log('Found new referrer: ' + referrer);
scriptProperties.setProperty(referrer, report.rows[i].metricValues[0].value);
anythingNew = true;
newText += 'New referrer: ' + referrer + '\r\n';
}
}
}
if (anythingNew) {
MailApp.sendEmail(SendEmailTo, 'Found new referrers for ' + PropertyName + ' on ' + new Date(), newText);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment