-
Notifications
You must be signed in to change notification settings - Fork 21
/
background.js
44 lines (42 loc) · 1.24 KB
/
background.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
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
console.log(request, sender);
const id = sender.tab.id;
if (request.action == "getSelection") {
chrome.scripting
.executeScript({
target: { tabId: id, allFrames: true },
func: () => {
return window.getSelection().toString();
},
})
.then((res) => {
console.log(res);
sendResponse({ data: res[0]["result"] });
});
} else if (request.action == "writeText") {
function writeTextToInput(text) {
const activeElement = document.activeElement;
if (
activeElement &&
(activeElement.tagName === "INPUT" ||
activeElement.tagName === "TEXTAREA")
) {
activeElement.value = `${activeElement.value}${text}`;
if (activeElement.tagName === "TEXTAREA") {
activeElement.scrollTop = activeElement.scrollHeight;
}
} else {
console.warn("No active input or textarea field found.");
}
}
chrome.scripting.executeScript({
target: { tabId: id, allFrames: true },
func: writeTextToInput,
args: [request.text],
});
sendResponse({});
} else {
sendResponse({});
}
return true;
});