-
Notifications
You must be signed in to change notification settings - Fork 1
/
co2.js
87 lines (71 loc) · 2.7 KB
/
co2.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// updating total co2 calculation
function update_total_co2() {
console.log("updating total co2");
let views = parseInt(document.getElementById('dupli_hit_counter').innerHTML);
let co2perview = parseFloat(document.getElementById('wcb_g').innerHTML.split("g")[0])
let out = (views * co2perview).toFixed(2);
if (!isNaN(out)) {
document.getElementById('total_emitted').innerHTML = out + "g";
}
}
// modified code from: https://gitlab.com/wholegrain/website-carbon-badges/-/blob/master/src/b.js
const $q = (selector) => document.getElementById(selector);
const wcb_url = encodeURIComponent(window.location.href)
const newRequest = function (render = true) {
// Run the API request because there is no cached result available
fetch('https://api.websitecarbon.com/b?url=' + wcb_url)
.then(function (r) {
if (!r.ok) {
throw Error(r);
}
return r.json();
})
.then(function (r) {
if (render) {
renderResult(r)
}
// Save the result into localStorage with a timestamp
r.t = new Date().getTime()
localStorage.setItem('wcb_'+wcb_url, JSON.stringify(r))
})
// Handle error responses
.catch(function (e) {
$q('wcb_g').innerHTML = 'No Result';
console.log(e);
localStorage.removeItem('wcb_'+wcb_url)
})
}
const renderResult = function (r) {
$q('wcb_g').innerHTML = r.c + ' g';
update_total_co2();
}
function wcb_update() {
if (('fetch' in window)) { // If the fetch API is not available, don't do anything.
// Get result if it's saved
let cachedResponse = localStorage.getItem('wcb_' + wcb_url)
const t = new Date().getTime()
// If there is a cached response, use it
if (cachedResponse) {
const r = JSON.parse(cachedResponse)
renderResult(r)
// If time since response was cached is over a day, then make a new request and update the cached result in the background
if ((t - r.t) > (86400000)) {
newRequest(false)
}
// If no cached response, then fetch from API
} else {
newRequest()
}
}
}
// handle visitorshitcounter
const Http = new XMLHttpRequest();
const url="https://visitorshitcounter.com/counterDisplay?code=f5708ccbf613d5194f97a38d4e8b99cf&style=0017&pad=5&type=page&initCount=1";
Http.open("GET", url);
Http.send();
Http.onreadystatechange = (e) => {
console.log("got http request: " + Http.responseText);
let views = Http.responseText;
document.getElementById('dupli_hit_counter').innerHTML = views;
update_total_co2();
}