-
Notifications
You must be signed in to change notification settings - Fork 0
/
content.js
76 lines (68 loc) · 2.84 KB
/
content.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
//By @ash-codes18 - Ashmit Mehta
const DISLIKE_ELE = `<div class="dislike_count"></div>`
async function manipulate() {
let url = window.location.href;
const match = url.match(/https:\/\/leetcode\.com\/problems\/([a-z0-9\-]+)/);
console.log("Running extension for ", url);
console.log("doing post req");
let response = await fetch("https://leetcode.com/graphql/", {
"headers": {
"content-type": "application/json"
},
"body": `{\"query\":\"\\n query questionTitle($titleSlug: String!) {\\n question(titleSlug: $titleSlug) {\\n dislikes\\n }\\n}\\n \",\"variables\":{\"titleSlug\":\"${match[1]}\"},\"operationName\":\"questionTitle\"}`,
"method": "POST"
});
let jresp = await response.json();
console.log("dislikes", jresp['data']['question']['dislikes']);
const flag = document.getElementsByClassName("dislike_count");
if (flag == null) {
let selector = document.querySelector("[data-icon='thumbs-down']").parentElement;
selector.insertAdjacentHTML('afterend', DISLIKE_ELE);
selector.parentElement.addEventListener('click', dislikeHandler);
}
document.getElementsByClassName("dislike_count")[0].innerHTML = jresp['data']['question']['dislikes'];
}
function waitForElm(selector) {
return new Promise(resolve => {
if (document.querySelector(selector)) {
return resolve(document.querySelector(selector));
}
const observer = new MutationObserver(mutations => {
if (document.querySelector(selector)) {
resolve(document.querySelector(selector));
observer.disconnect();
}
});
observer.observe(document.body, {
childList: true,
subtree: true
});
});
}
let toggled = false;
function dislikeHandler() {
toggled = !toggled;
const dislike_count = document.getElementsByClassName("dislike_count")[0]?.innerHTML;
if (dislike_count) {
document.getElementsByClassName("dislike_count")[0].innerHTML = parseInt(dislike_count) + (toggled ? 1 : -1);
}
}
waitForElm("[data-icon='thumbs-down']").then((elm) => {
console.log('Page reloaded');
let selector = document.querySelector("[data-icon='thumbs-down']").parentElement;
selector.insertAdjacentHTML('afterend', DISLIKE_ELE);
selector.parentElement.addEventListener('click', dislikeHandler);
manipulate();
});
let lastUrl = location.href;
new MutationObserver(() => {
const url = location.href;
const match = url.match(/https:\/\/leetcode\.com\/problems\/([a-z0-9\-]+)/);
if (!lastUrl.includes(match[1])) {
lastUrl = url;
waitForElm("[data-icon='thumbs-down']").then((elm) => {
console.log('Element is ready');
manipulate();
});
}
}).observe(document, { subtree: true, childList: true });