-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontent.js
58 lines (49 loc) · 1.48 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
let isXReplacementActive = true;
chrome.storage.local.get(
"isXReplacementActive",
({ isXReplacementActive: storedValue }) => {
isXReplacementActive = storedValue ?? true;
}
);
const REGEX = /\bX\b/gi;
const REPLACEMENT = "Twitter";
const TWEET_TEXT_SELECTOR = '[data-testid="tweetText"]';
function replaceContent(element) {
if (!isXReplacementActive) return;
if (element.nodeType === Node.TEXT_NODE) {
element.textContent = element.textContent.replace(REGEX, REPLACEMENT);
} else if (
element.nodeType === Node.ELEMENT_NODE &&
element.childNodes.length
) {
element.childNodes.forEach(replaceContent);
}
}
function processNewNodes(nodes) {
if (!isXReplacementActive) return;
nodes.forEach((node) => {
if (node.nodeType === Node.ELEMENT_NODE) {
node.querySelectorAll(TWEET_TEXT_SELECTOR).forEach(replaceContent);
}
});
}
document.querySelectorAll(TWEET_TEXT_SELECTOR).forEach(replaceContent);
// Observe for new tweets
new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (mutation.type === "childList") {
processNewNodes(mutation.addedNodes);
}
});
}).observe(document.body, { childList: true, subtree: true });
chrome.runtime.onMessage.addListener(({ action, enabled }) => {
if (action === "toggleReplacement") {
isXReplacementActive = enabled;
chrome.storage.local.set({ isXReplacementActive });
if (isXReplacementActive) {
document.querySelectorAll(TWEET_TEXT_SELECTOR).forEach(replaceContent);
} else {
location.reload();
}
}
});