Last active
April 25, 2022 15:18
-
-
Save bactisme/04ff2205ff4e97895c82ab2f1c21d76d to your computer and use it in GitHub Desktop.
Fetch data from plausible instance for an URL in Google Sheet
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
function PLAUSIBLE(url, period, fields) { | |
/** | |
* This function call plausible API, and can be use from Google Sheet | |
* url : The full url to the page | |
* period : control the period. Possible value : "day" (today, default), "6mo", "12mo", "30d", "7d", or "custom&date=2022-04-22,2022-04-22". | |
* fields : by default "visitors,visits,pageviews". A coma separated list of field returned. Can also be bounce_rate, visit_duration | |
* | |
* full doc : https://plausible.io/docs/stats-api#filtering | |
*/ | |
var BASE_URL = ""; | |
var TOKEN = ""; | |
// extract domain | |
var regExp = new RegExp("((?:[a-z]*)\.(?:com|fr))\/", "gi"); | |
var domain = regExp.exec(url)[1]; | |
var page = url.substring(url.indexOf(domain)+domain.length); | |
if (!period){ period = "day"; } // no date = today | |
if (!fields){ fields = "visitors,visits,pageviews" } | |
var fields_array = fields.split(","); | |
var plusOptions = { "headers" : { "Authorization" : "Bearer " + TOKEN } }; | |
var apiurl = BASE_URL+"/api/v1/stats/aggregate?site_id="+domain+"&period="+period+"&metrics="+fields+"&&filters=event:page==" + page; | |
var response = UrlFetchApp.fetch(apiurl, plusOptions); | |
var data = JSON.parse(response.getContentText()); | |
if (data){ | |
var results = data['results']; | |
var obj = []; | |
for(var i = 0; i < fields_array.length; i++){ | |
obj.push(results[fields_array[i]]['value']); | |
} | |
return [obj]; // double array for line printing | |
}else{ | |
return "Error"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment