-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathcontent.js
executable file
·385 lines (322 loc) · 11.4 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
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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
// Main script that works on chrome pages
(() => {
async function fetchDictionary() {
try {
response = await fetch(
// "https://z4kly0zbd9.execute-api.us-east-1.amazonaws.com/prod/translation",
// {
// method: "GET",
// }
"https://api.jsonbin.io/v3/b/669bb785e41b4d34e41497e4",
{
method: "GET",
headers: {
"X-Access-Key":
"$2a$10$D40ON/o9o/wDGqEu281T5e/t.DQ8NipDJAXRYc/conOeNaUuvxIRS",
},
}
);
data = await response.json();
console.log("data is ", data);
const dictionary = data["record"];
if (dictionary == null || typeof dictionary === "undefined") {
textToChange = false;
return;
}
dictionary["israel"] = "Palestine";
await chrome.storage.sync.set({ dictionary: dictionary }, () => {});
await chrome.storage.local.set({ dictionary: dictionary });
saveDictionaryToLocalStorage(dictionary);
return dictionary;
} catch (error) {
console.error("Error fetching dictionary:", error);
}
}
// Function to save dictionary to local storage
function saveDictionaryToLocalStorage(dictionary) {
const timestamp = new Date();
localStorage.setItem("dictionary", JSON.stringify(dictionary));
localStorage.setItem("dictionaryTimestamp", timestamp.toISOString());
}
// Function to check if a week has passed since the last update
function isWeekPassed(timestamp) {
const now = new Date();
const weekInMilliseconds = 7 * 24 * 60 * 60 * 1000;
let x=0
if (now -timestamp>weekInMilliseconds){
return true
}
else{
return false
}
}
// Function to get dictionary from local storage
function getDictionaryFromLocalStorage() {
const dictionary = localStorage.getItem("dictionary");
const timestamp = localStorage.getItem("dictionaryTimestamp");
if (dictionary && timestamp) {
return {
data: JSON.parse(dictionary),
timestamp: new Date(timestamp),
};
}
return null;
}
// Main function to get dictionary
async function getDictionary() {
let dictionaryData = getDictionaryFromLocalStorage();
if (dictionaryData && !isWeekPassed(dictionaryData.timestamp)) {
console.log("not fetching")
return dictionaryData.data;
}
console.log("fetchingg")
const newDictionary= await fetchDictionary();
if(newDictionary){
saveDictionaryToLocalStorage(newDictionary)
}
return newDictionary
}
let textToChange;
let regex;
const replacedWords = [];
const replacedSet = new Set();
const getReplacementText = (text) => {
let replacement = textToChange[text.toLowerCase()];
if (!replacement) {
return text;
}
if (text.charAt(0) === text.charAt(0).toUpperCase()) {
replacement = replacement.charAt(0).toUpperCase() + replacement.slice(1);
}
return replacement;
};
class BloomFilter {
constructor(size, numHashFunctions) {
if (size <= 0 || numHashFunctions <= 0) {
throw new Error("Size and number of hash functions must be positive integers.");
}
this.size = size;
this.numHashFunctions = numHashFunctions;
this.bitArray = new Array(size).fill(false);
}
//dwdwe
// Improved hash function with better distribution
hash(value, i) {
const hash1 = this.simpleHash(value, i);
const hash2 = this.simpleHash(value.split("").reverse().join(""), i + 1);
return (hash1 + i * hash2) % this.size;
}
// Simple hash function for demonstration
simpleHash(value, salt) {
let hash = 0;
for (let char of value) {
hash = (hash * salt + char.charCodeAt(0)) % this.size;
}
return hash;
}
// Add an item to the Bloom filter
add(value) {
for (let i = 0; i < this.numHashFunctions; i++) {
const index = this.hash(value, i);
this.bitArray[index] = true;
}
}
// Check if an item might be in the Bloom filter
contains(value) {
for (let i = 0; i < this.numHashFunctions; i++) {
const index = this.hash(value, i);
if (!this.bitArray[index]) {
return false; // Must be in all positions to return true
}
}
return false
}
}
const replaceText = (el,bloom) => {
if (el.nodeType === Node.TEXT_NODE) {
const words = el.textContent.split(regex);
const updatedText = words
.map((word) => {
const key = word.toLowerCase();
if (!bloom.contains(key)) {
if(textToChange[key]){
createTooltip(el,word)
return textToChange[key]
}
}
return word;
})
.join("");
el.textContent = updatedText;
} else {
for (let child of el.childNodes) {
replaceText(child,bloom);
}
}
};
// replacing images function
const replaceImages = () => {
// Locate the container of the flag by its class or other attributes
const flagContainer = document.querySelector("div.MRI68d");
if (flagContainer) {
// Locate the <img> element inside the container
const flagImage = flagContainer.querySelector("img");
if (flagImage) {
// Replace the image source with your custom image
const newImageUrl = chrome.runtime.getURL("images/Palestine_Flag.png");
flagImage.src = newImageUrl; // Update the image source
flagImage.alt = "Replaced Flag"; // Optionally update the alt text
}
}
};
const anyChildOfBody = "/html/body//";
// const doesNotContainAncestorWithRoleTextbox =
// "div[not(ancestor-or-self::*[@role=textbox])]/";
const isTextButNotPartOfJsScriptOrTooltip = "text()[not(parent::script) and not(ancestor::*[contains(@class, 'tooltip')])]";
const xpathExpression =
anyChildOfBody +
// + doesNotContainAncestorWithRoleTextbox;
isTextButNotPartOfJsScriptOrTooltip;
const replaceTextInNodes = () => {
if (regex == null || typeof regex === "undefined") {
return;
}
const times = [];
// Initialize the Bloom Filter
const bloom= new BloomFilter(1440,1) // Adjust size and number of hash functions
Object.keys(textToChange || {}).forEach((word) => bloom.add(word));
const result = document.evaluate(
xpathExpression,
document,
null,
XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
null
);
console.log(result);
for (let i = 0; i < result.snapshotLength; i++) {
// Call the replaceText function
replaceText(result.snapshotItem(i),bloom);
}
chrome.storage.local.set({
replacedWords: replacedWords,
replacedSet: replacedSet,
});
};
// integrating the 'replaceTextInNodes' and 'replaceImages' functions
const replaceTextAndImages = () => {
replaceTextInNodes(); // Call text replacement function
replaceImages(); // Call image replacement function
};
chrome.storage.sync.get(["ext_on"], async function (items) {
if (chrome.runtime.lastError) {
console.error(chrome.runtime.lastError);
return;
}
if (items.ext_on === false) {
return;
}
if (textToChange === false) {
return;
}
if (textToChange == null || typeof textToChange === "undefined") {
textToChange = await getDictionary();
if (textToChange == null || typeof textToChange === "undefined") {
return;
}
regex = new RegExp(
"\\b(" + Object.keys(textToChange).join("|") + ")\\b",
"gi"
);
}
if (replacedWords.length > 0) {
chrome.storage.local.set({
replacedWords: replacedWords,
replacedSet: replacedSet,
});
}
let timeout;
let lastRun = performance.now();
const observer = new MutationObserver((mutations) => {
const shouldUpdate = mutations.some((mutation) => {
return mutation.type === "childList" && mutation.addedNodes.length > 0;
});
if (!shouldUpdate) {
return;
}
if (performance.now() - lastRun < 3000) {
clearTimeout(timeout);
timeout = setTimeout(() => {
replaceTextAndImages();
lastRun = performance.now();
}, 600);
} else {
replaceTextAndImages();
lastRun = performance.now();
}
});
observer.observe(document, {
childList: true,
subtree: true,
attributes: false,
characterData: false,
characterDataOldValue: false,
});
chrome.storage.sync.get(["ext_on"], async function (items) {
if (chrome.runtime.lastError) {
console.error(chrome.runtime.lastError);
return;
}
if (items.ext_on === false) {
return;
}
replaceTextAndImages(); // Initial replacement when the extension is active
});
});
const createTooltip = (el, text) => {
const newElement = document.createElement("div");
const haifaText =
"Haifa was raided and occupied on April 22–23, 1948, after a major assault by the Haganah terrorists against Palestinian civilians. The Zionist terrorists drove the Palestinian residents to the sea under the threat of being shot cold in the street, thus emptying a large portion of the Palestinian population in Haifa.";
const jerusalemText =
"Jerusalem, an eternal capital of Palestinians, was raided by Zionist terrorist forces with the help of British soldiers who were occupying Jerusalem in April 1948, culminating with the division of the city by mid-May between the Hagana terrorists and Palestinians. Western Jerusalem fell to the occupation of the Zionist terrorists, while the Old City was taken by Jordanian forces on May 28, 1948.";
const nazarethText =
"Zionist terrorists raided Nazareth on July 16, 1948. After the Palestinians surrendered to the terrorists, they continued to massacre the inhabitants until a pact was made, and an-Nasra still houses the largest Palestinian native population in the occupied land.";
const toolTipText =
text == "Haifa" || text == "haifa"
? haifaText
: text == "Jerusalem" || text == "jerusalem"
? jerusalemText
: text == "Nazareth" || text == "nazareth"
? nazarethText
: text;
newElement.innerText = toolTipText;
newElement.classList.add("tooltip");
newElement.style.position = "absolute";
newElement.style.backgroundColor = "black";
newElement.style.color = "white";
newElement.style.padding = "5px";
newElement.style.borderRadius = "5px";
newElement.style.fontSize = "12px";
newElement.style.visibility = "hidden";
newElement.style.zIndex = "1000";
// Create a link element and wrap the tooltip
// const link = document.createElement("a");
// link.href = `https://www.palestineremembered.com/Search.html#gsc.tab=0&gsc.sort=&gsc.q=${encodeURIComponent(
// text
// )}`;
// link.target = "_blank"; // Opens the link in a new tab
// link.appendChild(newElement);
document.body.appendChild(newElement);
const parentNode = el.parentNode;
parentNode.addEventListener("mouseenter", function () {
const rect = parentNode.getBoundingClientRect(); // Get the element's position
newElement.style.left = `${rect.left + window.scrollX}px`;
newElement.style.top = `${
rect.top + window.scrollY - newElement.offsetHeight
}px`;
newElement.style.visibility = "visible";
});
parentNode.addEventListener("mouseleave", function () {
newElement.style.visibility = "hidden";
});
};
})();