-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
99 lines (86 loc) · 2.93 KB
/
content.js
File metadata and controls
99 lines (86 loc) · 2.93 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
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
88
89
90
91
92
93
94
95
96
97
98
99
const githubAvatarURL = (profileId) => `https://avatars.githubusercontent.com/u/${profileId}` ;
function applyReplacements() {
chrome.storage.sync.get(['sites'], (data) => {
const sites = data.sites || [];
const currentUrl = window.location.href;
sites.forEach((site) => {
if (site.url && (new RegExp(site.url)).test(currentUrl)) {
site.imageSettings.forEach((setting) => {
if (!setting.disabled && setting.url) {
let selector = setting.selector;
if (site.type === 'github' && setting.profileId) {
const avatar = githubAvatarURL(setting.profileId);
selector = `img[src^="${avatar}"]`;
}
if (selector) {
const elements = document.querySelectorAll(selector);
elements.forEach((el) => {
if (el.tagName === 'IMG') {
el.src = setting.url;
// For GitHub but may be needed everywhere?
if(el.style.height === 'auto')
el.style.height = null;
} else {
el.style.backgroundImage = `url(${setting.url})`;
}
});
}
}
});
site.textSettings.forEach((setting) => {
if (!setting.disabled && setting.search && setting.replacement) {
const walker = document.createTreeWalker(
document.body,
NodeFilter.SHOW_TEXT,
{
acceptNode: (node) => {
return node.parentElement.tagName !== 'SCRIPT' &&
node.parentElement.tagName !== 'STYLE'
? NodeFilter.FILTER_ACCEPT
: NodeFilter.FILTER_REJECT;
},
}
);
const nodes = [];
let node;
while ((node = walker.nextNode())) {
nodes.push(node);
}
nodes.forEach((textNode) => {
if (textNode.nodeValue.includes(setting.search)) {
textNode.nodeValue = textNode.nodeValue.replace(
new RegExp(setting.search, 'g'),
setting.replacement
);
}
});
}
});
}
});
});
}
// Run replacements on initial load
applyReplacements();
// Set up MutationObserver to handle dynamic DOM changes
const observer = new MutationObserver((mutations) => {
// Throttle to avoid excessive calls
let timeout;
clearTimeout(timeout);
timeout = setTimeout(() => {
applyReplacements();
}, 100);
});
// Observe changes to the body and its subtree
observer.observe(document.body, {
childList: true,
subtree: true
});
// Handle Turbo-specific events
document.addEventListener('turbo:load', () => {
applyReplacements();
});
// Ensure replacements persist on Turbo frame updates
document.addEventListener('turbo:render', () => {
applyReplacements();
});