Skip to content

Instantly share code, notes, and snippets.

@coffee-mug
Created November 14, 2019 14:32
Show Gist options
  • Save coffee-mug/42179a3747accdfd1277e552fdbb4ba9 to your computer and use it in GitHub Desktop.
Save coffee-mug/42179a3747accdfd1277e552fdbb4ba9 to your computer and use it in GitHub Desktop.
Create GA Custom Dimensions from a javascript array - no API.
/** UTILS **/
async function after(delay, fn) {
return new Promise((resolve, reject) => {
let to = setTimeout(function () {
resolve(fn());
clearTimeout(to);
}, delay)
})
}
/** Utils to withdraw the cusotm dims from G Sheet */
function strToObjArray(str) {
return str.split('\n').map(row => { let r = row.split('\t'); return { 'index': r[0], 'name': r[2].trim(), 'scope': r[1] == "USER" ? "VISITOR" : r[1].toUpperCase(), 'active': true } })
}
/** Fill an array to maxSize with null values */
function fillArray(arr, maxSize) {
// for each item in arr
let arrCopy = new Array(maxSize).fill(null)
arr.forEach(cd => {
if (cd && cd.index) {
arrCopy[Number(cd.index)] = cd
}
})
return arrCopy;
}
function lastDimIndex() {
// must be calle don the dimensions list page
let lastDimension = Array.from(document.querySelectorAll('tr[class^="ID-row"]')).pop().children[1].textContent;
return Number(lastDimension) || 1
}
function addCd() {
let addDimButton = document.querySelector("div.ID-adminTableControl button")
addDimButton.click();
}
function editCd(name, scope, active) {
/*************
* CD screen *
**************/
// Fill Name
let nameField = document.querySelector('input[data-name="dimensionName"]')
nameField.value = name;
// Fill scope
let scopeField = document.querySelector(`li[data-value=${scope.toUpperCase()}]`).click()
// active or not ?
let dimensionActive = document.querySelector('span[data-name="dimensionActive"]')
if (dimensionActive.getAttribute('aria-checked') != String(active)) {
dimensionActive.click();
}
}
async function addDimension(cd) {
// Click the add new cd button
addCd();
// On dimensions edit page
if (cd) {
await after(2000, () => editCd(cd.name, cd.scope, cd.active))
} else {
// default cd
await after(2000, () => editCd("Not set", "HIT", false))
}
// Save it
let saveButton = document.querySelector('button[data-name="actionFormButton"]')
await after(2000, () => saveButton.click())
// Validate our newly created dimension, clicking the "Done" button
await after(2000, () => {
let okCreatedButton = document.querySelector('button[data-name="cancelFormButton"]');
okCreatedButton.click()
})
}
async function main(customDims, startIndex = 1, endIndex) {
// for evry index between m and n
// if we have a custom dim at index m of our update table which is not null
// use his infos to edit the cd. Otherwise, fill it as an inactive custom dim.
if (!customDims) { throw new Error("main must be called with an array of custom dim objects, quitting.") }
for (startIndex; startIndex < endIndex; startIndex++) {
let cd = customDims[startIndex]
addDimension(cd)
await after(2000, () => console.log(`Custom dim processed - ${startIndex}`))
}
}
// How many dimensions already exist ?
var nextDimIdx = lastDimIndex();
// cdsList starts at index 1
// to generate the list
// 1/ copy paste the tablea into a string
// 2/ Get the array strToObjArray(str)
// 2/ Get the complete array with fillArray(arr, maxSize)
// Here maxSize is the total count of custom dims
cdsList = [null, { "index": "2", "name": "My Custom Dim", "scope": "HIT", "active": true }]
main(cdsList, nextDimIdx + 1, cdsList.length);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment