-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
267 lines (251 loc) · 10 KB
/
content.js
File metadata and controls
267 lines (251 loc) · 10 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
// Escape Hatch content script
(function () {
'use strict';
// Common sets and constants
const REJECT_TAGS = new Set(['script', 'style', 'textarea', 'input', 'select', 'button', 'a', 'noscript', 'iframe']);
const ACTION_RUN = 'runreplacements';
// Utility: walk the DOM and find text nodes
function walk(root, callback) {
// Recursive walk that descends into shadow roots and document fragments
function visit(node) {
if (!node) return;
if (node.nodeType === Node.TEXT_NODE) {
if (!node.nodeValue || !node.nodeValue.trim()) return;
// ensure not inside an ignored ancestor chain
let ancestor = node.parentNode;
if (!ancestor) return;
while (ancestor) {
const tag = ancestor.nodeName && ancestor.nodeName.toLowerCase();
if (tag && REJECT_TAGS.has(tag)) return;
if (ancestor.isContentEditable) return;
// stop at provided root to avoid crossing context
if (ancestor === root) break;
ancestor = ancestor.parentNode;
}
callback(node);
return;
}
// If element has a shadow root, traverse it
if (node.nodeType === Node.ELEMENT_NODE) {
const el = node;
if (el.shadowRoot) visit(el.shadowRoot);
}
// traverse child nodes and document fragments
const children = node.childNodes && Array.from(node.childNodes) || [];
for (const c of children) visit(c);
}
visit(root);
}
// Escape regex special chars in a string
function escapeRegex(s) {
return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
// Build a flexible regex pattern from a literal find string.
// - Treat spaces as \s+ (match any whitespace)
// - Treat hyphen-minus as a class matching common dash characters and non-breaking hyphen
function buildFlexiblePattern(find) {
let s = escapeRegex(find);
// Normalize whitespace in pattern to match any whitespace sequences
s = s.replace(/\\s\+/g, '\\s+'); // no-op if already
s = s.replace(/\s+/g, '\\s+');
// Replace literal hyphen-minus with a class matching common dash chars (include hyphen-minus itself)
s = s.replace(/-/g, '[-\\u2010-\\u2015\\u2212\\u2012\\u2013\\u2014\\u2011\\-]');
return s;
}
// Centralized regex creation for a literal find string (global + case-insensitive)
function getRegexForFind(find) {
const pattern = buildFlexiblePattern(find || '');
return new RegExp(pattern, 'gi');
}
// Apply replacements to a text node's value
function applyReplacementsToText(node, replacements) {
let text = node.nodeValue;
let changed = false;
for (const { find, replace } of replacements) {
if (!find) continue;
const re = getRegexForFind(find);
re.lastIndex = 0;
if (re.test(text)) {
text = text.replace(re, (match) => {
changed = true;
// Preserve capitalization of first letter
if (match[0] === match[0].toUpperCase()) {
return replace.charAt(0).toUpperCase() + replace.slice(1);
}
return replace;
});
}
}
if (changed) node.nodeValue = text;
}
// Collect visible text nodes under root using same filter rules
function collectTextNodes(root) {
const nodes = [];
function visit(node) {
if (!node) return;
if (node.nodeType === Node.TEXT_NODE) {
if (!node.nodeValue || !node.nodeValue.trim()) return;
let ancestor = node.parentNode;
if (!ancestor) return;
while (ancestor) {
const tag = ancestor.nodeName && ancestor.nodeName.toLowerCase();
if (tag && REJECT_TAGS.has(tag)) return;
if (ancestor.isContentEditable) return;
// stop at root to avoid crossing context
if (ancestor === root) break;
ancestor = ancestor.parentNode;
}
nodes.push(node);
return;
}
if (node.nodeType === Node.ELEMENT_NODE) {
const el = node;
if (el.shadowRoot) visit(el.shadowRoot);
}
const children = node.childNodes && Array.from(node.childNodes) || [];
for (const c of children) visit(c);
}
visit(root);
return nodes;
}
// Replace across multiple text nodes using Range so matches that span nodes are handled
function replaceAcrossTextNodes(root, replacements) {
// Keep applying replacements until nothing changes for each replacement (safer index handling)
for (const { find, replace } of replacements) {
if (!find) continue;
const re = getRegexForFind(find);
let madeChange = true;
while (madeChange) {
madeChange = false;
const nodes = collectTextNodes(root);
if (!nodes.length) break;
const texts = nodes.map(n => n.nodeValue);
const prefix = [];
let acc = 0;
for (let i = 0; i < texts.length; i++) {
prefix.push(acc);
acc += texts[i].length;
}
const combined = texts.join('');
re.lastIndex = 0;
const m = re.exec(combined);
if (m && typeof m.index === 'number') {
const startIndex = m.index;
const endIndex = m.index + m[0].length;
// find start node
let startNodeIndex = prefix.length - 1;
for (let i = 0; i < prefix.length; i++) {
if (startIndex >= prefix[i] && startIndex < (prefix[i] + texts[i].length)) { startNodeIndex = i; break; }
}
let endNodeIndex = prefix.length - 1;
for (let i = 0; i < prefix.length; i++) {
if (endIndex > prefix[i] && endIndex <= (prefix[i] + texts[i].length)) { endNodeIndex = i; break; }
}
const startNode = nodes[startNodeIndex];
const endNode = nodes[endNodeIndex];
const startOffset = startIndex - prefix[startNodeIndex];
const endOffset = endIndex - prefix[endNodeIndex];
// adjust replacement capitalization based on matched text
const matchedText = m[0];
const finalReplacement = (matchedText[0] === matchedText[0].toUpperCase()) ? (replace.charAt(0).toUpperCase() + replace.slice(1)) : replace;
const range = document.createRange();
try {
range.setStart(startNode, startOffset);
range.setEnd(endNode, endOffset);
range.deleteContents();
range.insertNode(document.createTextNode(finalReplacement));
madeChange = true;
} catch (e) {
// If Range failed for any reason, bail out to avoid corrupting DOM
console.warn('Escape Hatch: Range replacement failed', e);
madeChange = false;
break;
} finally {
range.detach && range.detach();
}
}
}
}
}
// Main: load settings and run
function init() {
// Content script only uses user-saved custom phrases. Defaults are intentionally not applied
// automatically by the content script; they are shown in the options UI as pre-populated inputs.
const getDefaults = () => [];
const obsOptions = { childList: true, subtree: true };
let observer = null;
let scheduled = null;
const runWithDefaults = (custom) => {
// Only user-saved custom phrases are used by the content script.
const all = Array.isArray(custom) ? custom : [];
// Normalize phrases: ensure objects with find/replace
const replacements = all.map(p => ({ find: p.find || p[0] || '', replace: p.replace || p[1] || '' })).filter(p => p.find && p.replace);
// First attempt robust replacements across nodes
// Disconnect observer while applying to avoid reacting to our own DOM edits
if (observer) observer.disconnect();
try {
replaceAcrossTextNodes(document.body, replacements);
// Also run single-node replacements as a fallback for any remaining matches
walk(document.body, node => applyReplacementsToText(node, replacements));
} finally {
// reconnect
if (observer) observer.observe(document.body, obsOptions);
}
};
// Listen for messages to re-run replacements (e.g., from popup)
try {
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
if (msg && typeof msg.action === 'string' && msg.action.toLowerCase() === 'runreplacements') {
if (chrome.storage && chrome.storage.sync) {
chrome.storage.sync.get(['enabled', 'customPhrases'], (res) => {
const enabled = res.enabled === true;
if (!enabled) return;
const custom = Array.isArray(res.customPhrases) ? res.customPhrases : [];
runWithDefaults(custom);
});
} else {
runWithDefaults([]);
}
}
});
} catch (e) { /* ignore in contexts without runtime */ }
if (chrome.storage && chrome.storage.sync) {
chrome.storage.sync.get(['enabled', 'customPhrases'], (res) => {
const enabled = res.enabled === true;
if (!enabled) return;
const custom = Array.isArray(res.customPhrases) ? res.customPhrases : [];
runWithDefaults(custom);
});
} else {
// Fallback if chrome.storage not present
runWithDefaults([]);
}
// Observe for dynamic changes and re-run replacements on new content (debounced)
function debounceRun(custom) {
if (scheduled) clearTimeout(scheduled);
scheduled = setTimeout(() => {
scheduled = null;
try {
runWithDefaults(custom);
} catch (e) {
console.warn('Escape Hatch: replacement run failed', e);
}
}, 250);
}
if (document.body) {
observer = new MutationObserver((mutations) => {
// If there are added nodes, attempt to run replacements (debounced)
for (const m of mutations) {
if (m.addedNodes && m.addedNodes.length) { debounceRun([]); break; }
}
});
try { observer.observe(document.body, obsOptions); } catch (e) { /* ignore */ }
}
}
// Run when DOMContentLoaded or immediately if already loaded
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init);
} else {
init();
}
})();