-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
260 lines (232 loc) · 9.2 KB
/
Copy pathbackground.js
File metadata and controls
260 lines (232 loc) · 9.2 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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
// background.js - OdooDevTools
/* ══════════════════════════════════════
Hash fragment helpers
══════════════════════════════════════ */
function parseHash(url) {
try {
const hash = new URL(url).hash.replace(/^#/, "");
if (!hash) return {};
return Object.fromEntries(
hash.split("&")
.filter((s) => s.includes("="))
.map((s) => s.split("=").map(decodeURIComponent))
);
} catch { return {}; }
}
function setHashParam(url, key, value) {
try {
const u = new URL(url);
const params = parseHash(url);
params[key] = value;
delete params["_company_switching"];
u.hash = Object.entries(params)
.map(([k, v]) => `${k}=${encodeURIComponent(v)}`)
.join("&");
return u.toString();
} catch { return url; }
}
function deleteHashParam(url, key) {
try {
const u = new URL(url);
const params = parseHash(url);
delete params[key];
delete params["_company_switching"];
const entries = Object.entries(params);
u.hash = entries.length
? entries.map(([k, v]) => `${k}=${encodeURIComponent(v)}`).join("&")
: "";
return u.toString();
} catch { return url; }
}
/* ══════════════════════════════════════
Storage
══════════════════════════════════════ */
async function getStorage() {
return new Promise((resolve) => {
chrome.storage.sync.get({ domains: [], companies: [], clientMode: false }, resolve);
});
}
/* ══════════════════════════════════════
Matching
══════════════════════════════════════ */
function matchEntry(url, entries) {
try {
const { hostname, host } = new URL(url);
return entries.find((e) => {
const clean = e.domain.replace(/^https?:\/\//, "").replace(/\/$/, "");
if (clean.includes(":")) return host === clean;
return hostname === clean || hostname.endsWith("." + clean);
}) || null;
} catch { return null; }
}
function isLoginPage(url) {
try {
const { pathname } = new URL(url);
return pathname === "/web/login" || pathname.startsWith("/web/login/");
} catch { return true; }
}
function isCompanySwitching(url) {
try {
return parseHash(url)["_company_switching"] === "1";
} catch { return false; }
}
function alreadyUpToDate(url, entry) {
try {
const searchParams = new URL(url).searchParams;
const hashParams = parseHash(url);
const debugOk = searchParams.get("debug") === (entry.mode || "1");
const langOk = !entry.lang || searchParams.get("lang") === entry.lang;
const cidsOk = !entry.cid || hashParams["cids"] === String(entry.cid);
return debugOk && langOk && cidsOk;
} catch { return false; }
}
function buildDebugUrl(url, entry) {
let result = url;
const u = new URL(result);
u.searchParams.set("debug", entry.mode || "1");
if (entry.lang) u.searchParams.set("lang", entry.lang);
else u.searchParams.delete("lang");
result = u.toString();
if (entry.cid) result = setHashParam(result, "cids", String(entry.cid));
return result;
}
function getDebugUrl(url, entries) {
if (!url.startsWith("http")) return null;
if (isLoginPage(url)) return null;
if (isCompanySwitching(url)) return null;
if (!entries.length) return null;
const entry = matchEntry(url, entries);
if (!entry) return null;
if (alreadyUpToDate(url, entry)) return null;
return buildDebugUrl(url, entry);
}
/* ══════════════════════════════════════
Badge
══════════════════════════════════════ */
async function updateBadge(tabId, url) {
if (!url || !url.startsWith("http")) {
chrome.action.setBadgeText({ text: "", tabId });
return;
}
const { domains, clientMode } = await getStorage();
// Modo cliente activo → badge gris con ojo
if (clientMode) {
const entry = matchEntry(url, domains);
if (entry) {
chrome.action.setBadgeText({ text: "👁", tabId });
chrome.action.setBadgeBackgroundColor({ color: "#f59e0b", tabId });
return;
}
}
const entry = matchEntry(url, domains);
if (!entry) {
chrome.action.setBadgeText({ text: "", tabId });
return;
}
let debugVal = null;
try { debugVal = new URL(url).searchParams.get("debug"); } catch {}
const setBadgeTextColor = chrome.action.setBadgeTextColor
? (opts) => chrome.action.setBadgeTextColor(opts)
: () => {};
if (debugVal === "1") {
chrome.action.setBadgeText({ text: "1", tabId });
chrome.action.setBadgeBackgroundColor({ color: "#22c55e", tabId });
chrome.action.setBadgeTextColor({ color: "#ffffff", tabId });
} else if (debugVal === "assets") {
chrome.action.setBadgeText({ text: "A", tabId });
chrome.action.setBadgeBackgroundColor({ color: "#f59e0b", tabId });
chrome.action.setBadgeTextColor({ color: "#ffffff", tabId });
} else {
chrome.action.setBadgeText({ text: "·", tabId });
chrome.action.setBadgeBackgroundColor({ color: "#6b7280", tabId });
chrome.action.setBadgeTextColor({ color: "#ffffff", tabId });
}
}
chrome.tabs.onActivated.addListener(async ({ tabId }) => {
try {
const tab = await chrome.tabs.get(tabId);
updateBadge(tabId, tab.url || "");
} catch {}
});
chrome.tabs.onUpdated.addListener((tabId, changeInfo) => {
if (changeInfo.url) updateBadge(tabId, changeInfo.url);
});
chrome.storage.onChanged.addListener(async (changes) => {
if (!changes.domains && !changes.clientMode) return;
try {
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
if (tab) updateBadge(tab.id, tab.url || "");
} catch {}
});
/* ══════════════════════════════════════
Detección de POST — evita redirigir durante
todo el flujo POST → 302 → página final,
preservando mensajes flash del servidor
══════════════════════════════════════ */
const postTabs = new Set();
chrome.webRequest.onBeforeRequest.addListener(
(details) => {
if (details.type === "main_frame" && details.method === "POST") {
postTabs.add(details.tabId);
}
},
{ urls: ["<all_urls>"] }
);
chrome.webNavigation.onCompleted.addListener((details) => {
if (details.frameId === 0) postTabs.delete(details.tabId);
});
chrome.webNavigation.onErrorOccurred.addListener((details) => {
if (details.frameId === 0) postTabs.delete(details.tabId);
});
chrome.tabs.onRemoved.addListener((tabId) => postTabs.delete(tabId));
/* ══════════════════════════════════════
Navegación — respeta modo cliente
══════════════════════════════════════ */
chrome.webNavigation.onBeforeNavigate.addListener(async (details) => {
if (details.frameId !== 0) return;
const { domains, clientMode } = await getStorage();
if (clientMode) return; // no interceptar en modo cliente
if (postTabs.has(details.tabId)) return;
const debugUrl = getDebugUrl(details.url, domains);
if (debugUrl) chrome.tabs.update(details.tabId, { url: debugUrl });
});
chrome.webNavigation.onCommitted.addListener(async (details) => {
if (details.frameId !== 0) return;
const qualifies =
(details.transitionQualifiers && details.transitionQualifiers.includes("server_redirect")) ||
details.transitionType === "form_submit";
if (!qualifies) return;
const { domains, clientMode } = await getStorage();
if (clientMode) return; // no interceptar en modo cliente
if (postTabs.has(details.tabId)) return;
const debugUrl = getDebugUrl(details.url, domains);
if (debugUrl) chrome.tabs.update(details.tabId, { url: debugUrl });
});
/* ══════════════════════════════════════
Borrar action temporal creado por openModel
El popup se cierra al navegar, así que el
unlink lo ejecuta el background que permanece vivo
══════════════════════════════════════ */
chrome.runtime.onMessage.addListener((msg) => {
if (msg.type !== "unlinkAction") return;
const { origin, actionId } = msg;
// Esperar a que Odoo haya cargado el action en cliente antes de borrarlo
setTimeout(async () => {
try {
await fetch(`${origin}/web/dataset/call_kw`, {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
body: JSON.stringify({
jsonrpc: "2.0", method: "call", id: 1,
params: {
model: "ir.actions.act_window",
method: "unlink",
args: [[actionId]],
kwargs: {}
}
})
});
} catch {}
}, 3000);
});