Skip to content

Instantly share code, notes, and snippets.

@woutervdijke
Created January 13, 2022 23:03
Show Gist options
  • Save woutervdijke/724bc1443954a88d3da4c05e81720584 to your computer and use it in GitHub Desktop.
Save woutervdijke/724bc1443954a88d3da4c05e81720584 to your computer and use it in GitHub Desktop.
Bookmarklet to select data from a graph on Our World in Data, and copy it to the clipboard.
function getOwidData(){
var filteredCountry = [];
var filteredTime = [];
filteredCountry = grapher.mappableData.filter((obj) => Object.values(grapher.selection.selectedEntityNames).indexOf(obj.entityName) > -1); // first, filter the entire data set to just the selected countries
filteredTime = filteredCountry.filter((obj) => obj.time >= grapher.minTime && obj.time <= grapher.maxTime); // then, filter it further to only the selected time period
filteredTime.forEach(x => x.time = grapher.formatTime(x.time)); // convert timestamp to actual dates
filteredTime.forEach(x => x.value = x.value.toString().replace('.',',')); // convert to decimal commas for European Excel
return filteredTime;
}
function jsonToExcel(json) { // convert json data to a format Excel understands
var fields = Object.keys(json[0]);
var replacer = function(key, value) { return value === null ? '' : value } ;
var csv = json.map(function(row){
return fields.map(function(fieldName){
return JSON.stringify(row[fieldName], replacer);
}).join('\t');
});
csv.unshift(fields.join('\t'));
csv = csv.join('\r\n');
return csv;
}
function copyStringToClipboard (str) { // Copy data to clipboard through a fake invisible textarea
var el = document.createElement('textarea');
el.value = str;
el.setAttribute('readonly', '');
el.style = {position: 'absolute', left: '-9999px'};
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);
}
if (window.location.href.split('/')[2] == 'ourworldindata.org'){ // alert user if not on the right site
var owidData = getOwidData();
var excelData = jsonToExcel(owidData);
copyStringToClipboard(excelData);
void(alert('Data copied to clipboard'));
} else {
alert('This bookmarklet only works on ourworldindata.org')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment