-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontent_script.js
57 lines (52 loc) · 1.43 KB
/
content_script.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
var browser = browser || chrome
var originals = []
var existingLocale = "en"
function loadLocalization(lang) {
let URL = browser.runtime.getURL(`data/${lang}/${lang}.json`)
console.log("URL: ", URL)
window
.fetch(URL)
.then((res) => res.json())
.then((strings) => {
var translations = JSON.parse(JSON.stringify(strings))
const elementsInsideBody = [...document.body.getElementsByTagName("*")]
findAndReplace(elementsInsideBody, translations)
})
}
/**
* A function that loops through every single item
* @param {*} elementsInsideBody
*/
//
function findAndReplace(elementsInsideBody, translations) {
elementsInsideBody.forEach((element) => {
element.childNodes.forEach((child) => {
if (child.nodeType === 3) {
replaceText(child, translations)
}
})
})
}
/**
* Regex Function to replace the node
* @param {*} node
*/
function replaceText(node, translations) {
let value = node.nodeValue
translations.map((obj) => {
const regexVariable = new RegExp(obj.word, "g")
value = value.replace(regexVariable, obj.replacedWord)
node.nodeValue = value
})
}
/*window.onload = (event) => {
loadLocalization("te");
};*/
browser.runtime.onMessage.addListener(function (request, sender, sendResponse) {
var data = request.data || {}
if (data.lang == "en") {
location.reload()
}
loadLocalization(data.lang)
sendResponse({ data: { message: "success" }, success: true })
})