Last active
July 7, 2017 12:37
-
-
Save SiegHartR/c4589a8d3530b25cb304cfbb2a5d05a0 to your computer and use it in GitHub Desktop.
Find the desired GA view ID for your API call with only the URL of the page going through GTM - the aim is mainly to avoid any search into your accounts especially if you have to many property IDs and all with the same site url
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(httr) | |
library(XML) | |
library(googleAnalyticsR) | |
library(googleAuthR) | |
gwt_site_url <- "https://www.example.co.uk/" | |
html <- GET(gwt_site_url) | |
doc <- htmlParse(html) | |
attrs <- xpathApply(doc, "//iframe/@src") | |
gtm <- sapply(attrs, function(x) x[[1]]) | |
gtm_value <- grep("GTM-", gtm, value = TRUE) | |
gtm_value <- gsub("https:|//www.googletagmanager.com/ns.html\\?id=", "", gtm_value)[1] | |
GTMhtml <- GET(paste0("https://www.googletagmanager.com/gtm.js?id=", gtm_value)) | |
GTMdoc <- suppressWarnings(htmlParse(GTMhtml)) | |
GTMattrs <- unlist(xpathApply(GTMdoc, "//p", xmlValue)) | |
GAValue <- gsub("\\'.*","",gsub(".*UA-", "UA-",GTMattrs[2])) | |
gar_auth() | |
accounts <- ga_account_list() | |
accountsSite <- accounts[accounts$webPropertyId == GAValue,] | |
rownames(accountsSite) <- NULL | |
print(accountsSite) | |
n <- readline(prompt="Select view (row number): ") | |
GAviewID <- accountsSite$viewId[as.numeric(n)] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment