-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
53 lines (46 loc) · 1.71 KB
/
index.js
File metadata and controls
53 lines (46 loc) · 1.71 KB
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
(() => {
/*
The "Unicode Problem" of Base64 encoding and decoding
URL: https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#The_Unicode_Problem
*/
const b64EncodeUnicode = (str) => btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, (match, p1) => String.fromCharCode(`0x${p1}`)));
// -- End --
const {
databaseProvider,
databaseConfig,
} = window.wildfireConfig();
if (databaseProvider !== 'firebase' && databaseProvider !== 'wilddog') {
console.error('[wf-count] Invalid `databaseProvider`.');
return;
}
if (!databaseConfig) {
console.error('[wf-count] Missing wildfire config: `databaseConfig`.');
return;
}
let baseURL;
if (databaseProvider === 'firebase') {
baseURL = databaseConfig.databaseURL;
} else {
baseURL = `https://${databaseConfig.siteId}.wilddogio.com`;
}
const discussionCountEles = document.getElementsByClassName('wf-count-unit');
for (let i = 0; i < discussionCountEles.length; i += 1) {
const ele = discussionCountEles[i]
const pageURL = ele.getAttribute('wf-page-url');
if (!pageURL) {
console.error('[wf-count] Missing attribute: `wf-page-url`.');
return;
}
const url = `${baseURL}/pageComments/${b64EncodeUnicode(pageURL)}.json`;
fetch(url).then((response) => {
const contentType = response.headers.get('content-type');
if (contentType && contentType.includes('application/json')) {
return response.json();
}
throw new TypeError("Oops, we haven't got JSON!");
}).then((json) => {
const discussionCount = Object.keys(json || {}).length;
ele.innerHTML = discussionCount;
}).catch((error) => { console.error(error); });
}
})();