-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontentScript.js
More file actions
87 lines (74 loc) · 2.51 KB
/
Copy pathcontentScript.js
File metadata and controls
87 lines (74 loc) · 2.51 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
function modifyDOM() {
const paragraphs = document.querySelectorAll("p");
let paraArray = [];
let totalTokens = 0;
for (let i = 0; i < paragraphs.length; i++) {
const paraText = paragraphs[i].textContent;
const paraTokens = countTokens(paraText);
if (totalTokens + paraTokens < 1800) {
paraArray.push(paraText);
totalTokens += paraTokens;
} else {
break;
}
}
getResponseFromOpenAI(paraArray, (response) => {
const [res, translationQueue] = JSON.parse(response);
console.log(translationQueue);
for (let i = 0; i < res.length; i++) {
let paragraphTranslation = res[i];
const regex = /\$\#(.*?)\$\#/g;
let matches = [...paragraphTranslation.matchAll(regex)];
// Loop through each occurrence of the regex and replace them one by one
for (let match of matches) {
const originalText = translationQueue.shift();
paragraphTranslation = paragraphTranslation.replace(
match[0],
`<span class="hoverable" style="background-color: rgba(60, 162, 147, 0.5);" data-original="${originalText}">${match[1]}</span>`
);
}
paragraphs[i].innerHTML = paragraphTranslation;
}
attachHoverEvents();
});
}
function countTokens(text) {
return text.split(/\s+/).length;
}
modifyDOM();
function getResponseFromOpenAI(message, callback) {
chrome.runtime.sendMessage(
{ action: "translateText", prompt: message },
(response) => {
callback(response);
}
);
}
function attachHoverEvents() {
const hoverDiv = document.createElement("div");
hoverDiv.style.position = "absolute";
hoverDiv.style.backgroundColor = "#333";
hoverDiv.style.color = "white";
hoverDiv.style.padding = "5px";
hoverDiv.style.borderRadius = "5px";
hoverDiv.style.display = "none";
hoverDiv.style.zIndex = "1000";
document.body.appendChild(hoverDiv);
const hoverableSpans = document.querySelectorAll(".hoverable");
hoverableSpans.forEach((span) => {
span.addEventListener("mouseover", (e) => {
const originalContent = span.getAttribute("data-original");
hoverDiv.innerHTML = `Original: ${originalContent}`;
hoverDiv.style.display = "block";
hoverDiv.style.left = `${e.pageX + 10}px`;
hoverDiv.style.top = `${e.pageY + 10}px`;
});
span.addEventListener("mousemove", (e) => {
hoverDiv.style.left = `${e.pageX + 10}px`;
hoverDiv.style.top = `${e.pageY + 10}px`;
});
span.addEventListener("mouseout", () => {
hoverDiv.style.display = "none";
});
});
}