-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathbackground.js
More file actions
243 lines (219 loc) · 8.26 KB
/
background.js
File metadata and controls
243 lines (219 loc) · 8.26 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
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
const browserAppData = chrome || browser;
const tabs = {};
const inspectFile = 'inspect.js';
const activeIcon = 'zeuz-active.png';
const defaultIcon = 'zeuz.png';
var zeuz_url;
var zeuz_key;
var zeuz_node_id;
const _aiContentTimers = {}; // per-tab debounce for node_ai_contents
const _aiContentHashes = {}; // per-tab hashes to avoid resending unchanged contents
fetch("data.json")
.then(Response => Response.json())
.then(data => {
zeuz_url = data.url;
zeuz_key = data.apiKey;
zeuz_node_id = data.nodeId;
browserAppData.storage.local.set({
url: zeuz_url,
key: zeuz_key,
nodeId: zeuz_node_id,
},
function () {
console.log("Logged in successfully!");
});
});
function logout() {
browserAppData.storage.local.remove(['key'], function () {
alert("Logged out successfully!");
});
}
browserAppData.contextMenus.onClicked.addListener(logout);
const inspect = {
toggleActivate: (id, type, icon) => {
// this.id = id;
// browserAppData.tabs.executeScript(id, { file: inspectFile }, () => { browserAppData.tabs.sendMessage(id, { action: type }); });
// browserAppData.scripting.executeScript({
// target: {tabId: id},
// files: [inspectFile]
// });
browserAppData.tabs.sendMessage(id, {
action: type
}).then((response) => {
console.log("Message from the content script:");
console.log(response);
})
.catch((error) => {
console.error(`Error: ${error}`)
});
browserAppData.action.setIcon({
tabId: id,
path: {
19: icon
}
});
}
};
function isSupportedProtocolAndFileType(urlString) {
if (!urlString) {
return false;
}
const supportedProtocols = ['https:', 'http:', 'file:'];
const notSupportedFiles = ['xml', 'pdf', 'rss'];
const extension = urlString.split('.').pop().split(/\#|\?/)[0];
// const url = document.createElement('a');
// url.href = urlString;
const cond = supportedProtocols.indexOf(urlString.split("/")[0]) !== -1 && notSupportedFiles.indexOf(extension) === -1;
console.log(cond);
console.log(urlString.split("/")[0]);
return supportedProtocols.indexOf(urlString.split("/")[0]) !== -1 && notSupportedFiles.indexOf(extension) === -1;
}
function toggle(tab) {
console.log("toggle()");
if (!isSupportedProtocolAndFileType(tab.url)) return;
if (!tabs[tab.id]) {
tabs[tab.id] = Object.create(inspect);
inspect.toggleActivate(tab.id, 'activate', activeIcon);
}
else {
// deactivate plugin
inspect.toggleActivate(tab.id, 'deactivate', defaultIcon);
for (const tabId in tabs) {
if (tabId == tab.id) delete tabs[tabId];
}
}
}
function deactivateItem(tab) {
if (tab[0]) {
if (isSupportedProtocolAndFileType(tab[0].url)) {
for (const tabId in tabs) {
if (tabId == tab[0].id) {
delete tabs[tabId];
inspect.toggleActivate(tab[0].id, 'deactivate', defaultIcon);
}
}
}
}
}
function getActiveTab() {
browserAppData.tabs.query({
active: true,
currentWindow: true
}, tab => {
deactivateItem(tab);
});
}
browserAppData.commands.onCommand.addListener(command => {
if (command === 'toggle-xpath') {
browserAppData.tabs.query({
active: true,
currentWindow: true
}, tab => {
toggle(tab[0]);
});
}
});
browserAppData.tabs.onUpdated.addListener(getActiveTab);
browserAppData.action.onClicked.addListener(toggle);
console.log(navigator.userAgentData.platform);
if (navigator.userAgentData.platform.toLowerCase().includes('mac')) {
browserAppData.action.setTitle({
title: "Cmd + Shift + X"
});
}
browserAppData.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
if (request.action === 'toggle_from_content_script') {
// allows the floating button to trigger the toggle logic
toggle(sender.tab);
return;
}
if (request.apiName == 'ai_record_single_action') {
var url = `${zeuz_url}/ai_record_single_action/`
fetch(url, {
method: "POST",
headers: {
// "Content-Type": "application/json",
"X-Api-Key": zeuz_key,
},
body: request.data,
})
.then(response => response.json())
.then(text => { console.log(text); sendResponse(text); })
var url = `${zeuz_url}/node_ai_contents/`
fetch(url, {
method: "POST",
headers: {
// "Content-Type": "application/json",
"X-Api-Key": zeuz_key,
},
body: JSON.stringify({
"dom_web": { "dom": request.html },
"node_id": zeuz_node_id.toLowerCase()
}),
})
.then(response => response.json())
.then(text => { console.log(text); sendResponse(text); })
return true; // Will respond asynchronously.
} else if (request.apiName == 'node_ai_contents') {
const tabId = sender.tab ? sender.tab.id : 'unknown';
if (_aiContentTimers[tabId]) clearTimeout(_aiContentTimers[tabId]);
_aiContentTimers[tabId] = setTimeout(async () => {
delete _aiContentTimers[tabId];
const contentObj = { "dom": request.dom, "page_map": request.page_map, "page_map_json": request.page_map_json };
const contentStr = JSON.stringify(contentObj);
let hash = '';
try {
const msgUint8 = new TextEncoder().encode(contentStr);
const hashBuffer = await crypto.subtle.digest('SHA-256', msgUint8);
const hashArray = Array.from(new Uint8Array(hashBuffer));
hash = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
} catch (e) {
console.error("Error generating hash", e);
hash = contentStr.length.toString(); // Fallback
}
if (_aiContentHashes[tabId] === hash) {
console.log('node_ai_contents skipped, content unchanged for tab:', tabId, 'hash:', hash);
try { sendResponse({ status: "skipped" }); } catch (e) { }
return;
}
_aiContentHashes[tabId] = hash;
console.log('node_ai_contents sending, new hash for tab:', tabId, 'hash:', hash);
var url = `${zeuz_url}/node_ai_contents/`;
fetch(url, {
method: "POST",
headers: {
// "Content-Type": "application/json",
"X-Api-Key": zeuz_key,
},
body: JSON.stringify({
"dom_web": contentObj,
"node_id": zeuz_node_id
}),
})
.then(response => {
if (!response.ok) {
console.error("node_ai_contents failed with status:", response.status, response.statusText);
}
return response.json();
})
.then(text => { console.log("node_ai_contents response:", text); try { sendResponse(text); } catch (e) { } })
.catch(e => console.error("node_ai_contents fetch error:", e));
}, 2000);
return true; // Will respond asynchronously.
}
}
);
// add AI Inspector to the right click menu
browserAppData.runtime.onInstalled.addListener(() => {
browserAppData.contextMenus.create({
id: "toggle-ai-inspect",
title: "Inspect with AI",
contexts: ["all"]
});
});
browserAppData.contextMenus.onClicked.addListener((info, tab) => {
if (info.menuItemId === "toggle-ai-inspect" && tab) {
toggle(tab);
}
});