-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
88 lines (77 loc) · 2.86 KB
/
background.js
File metadata and controls
88 lines (77 loc) · 2.86 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
// background.js
chrome.action.onClicked.addListener((tab) => {
if (!tab) {
console.error("No active tab found.");
return;
}
if (chrome.sidePanel && typeof chrome.sidePanel.getOptions === "function") {
// Try to open the side panel
chrome.sidePanel.getOptions({ tabId: tab.id }, (panelInfo) => {
if (chrome.runtime.lastError) {
console.error("Error getting side panel info:", chrome.runtime.lastError.message);
return;
}
if (panelInfo && panelInfo.isOpen) {
console.log("Side panel is already open.");
} else {
console.log("Opening side panel...");
chrome.sidePanel.open({ tabId: tab.id }, () => {
if (chrome.runtime.lastError) {
console.error("Error opening side panel:", chrome.runtime.lastError.message);
} else {
console.log("Side panel opened successfully.");
}
});
}
});
} else {
// Fallback: Open a popup if sidePanel is not supported
console.warn("Side panel API is not available. Falling back to popup.");
chrome.tabs.sendMessage(tab.id, { action: "openPopup" });
}
});
// Handle messages from the side panel or popup
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.action === "replaceText") {
const { oldText, newText, tabId } = message;
chrome.scripting.executeScript({
target: { tabId, allFrames: false },
func: (oldTextToReplace, newTextToInject) => {
const activeElement = document.activeElement;
if (
activeElement &&
(activeElement.tagName === "INPUT" ||
activeElement.tagName === "TEXTAREA" ||
activeElement.isContentEditable)
) {
let currentValue;
if (activeElement.isContentEditable) {
currentValue = activeElement.innerHTML;
} else {
currentValue = activeElement.value;
}
const updatedValue = currentValue.replace(oldTextToReplace, newTextToInject);
if (activeElement.isContentEditable) {
activeElement.innerHTML = updatedValue;
} else {
activeElement.value = updatedValue;
}
activeElement.focus();
return { success: true };
} else {
console.error("No valid text box is focused.");
return { success: false };
}
},
args: [message.oldText, message.newText],
}, (results) => {
if (chrome.runtime.lastError) {
console.error("Error executing script:", chrome.runtime.lastError.message);
sendResponse({ success: false });
} else {
sendResponse(results[0]?.result || { success: false });
}
});
return true; // Keep the message channel open for async responses
}
});