Repository navigation
Expand file tree
/
Copy pathbackground.js
More file actions
304 lines (272 loc) · 10.9 KB
/
Copy pathbackground.js
File metadata and controls
304 lines (272 loc) · 10.9 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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
// 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);
});
}
/* Odoo 19 guarda las compañías activas en la cookie "cids". A diferencia
de Odoo 14-18, no refleja ese estado en la URL /odoo/... . */
chrome.runtime.onMessage.addListener((msg, _sender, sendResponse) => {
if (msg.type !== "setOdoo19Companies") return;
chrome.cookies.set({
url: `${msg.origin}/`,
name: "cids",
value: String(msg.cids),
path: "/",
expirationDate: Math.floor(Date.now() / 1000) + (60 * 60 * 24 * 30),
}, () => {
if (chrome.runtime.lastError) {
sendResponse({ ok: false, error: chrome.runtime.lastError.message });
} else {
sendResponse({ ok: true });
}
});
return true;
});
/* ══════════════════════════════════════
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;
}) || 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 {
const parsed = new URL(url);
return parseHash(url)["_company_switching"] === "1" || parsed.searchParams.get("_company_switching") === "1";
} catch { return false; }
}
/* Rutas del backend (/web... y /odoo...): ahí un ?lang= suelto provoca
"Invalid language code", así que se elimina. */
function isBackendPath(pathname) {
return pathname === "/web" || pathname.startsWith("/web/") ||
pathname === "/odoo" || pathname.startsWith("/odoo/");
}
function isNewRouter(pathname) {
return pathname === "/odoo" || pathname.startsWith("/odoo/");
}
function alreadyUpToDate(url, entry) {
try {
const searchParams = new URL(url).searchParams;
const hashParams = parseHash(url);
const debugOk = searchParams.get("debug") === (entry.mode || "1");
const isOdoo19 = new URL(url).pathname === "/odoo" || new URL(url).pathname.startsWith("/odoo/");
// En Odoo 19 la empresa activa está en la cookie "cids", no en la URL.
const cidsOk = isOdoo19 || !entry.cid || hashParams["cids"] === String(entry.cid);
const u = new URL(url);
// Odoo 18+ (/odoo): el idioma va por RPC, nunca por URL.
// Odoo ≤17 (/web): ?lang= como siempre; sin idioma elegido no debe quedar ninguno.
const langOk = isNewRouter(u.pathname)
? !searchParams.has("lang")
: entry.lang
? searchParams.get("lang") === entry.lang
: !(isBackendPath(u.pathname) && searchParams.has("lang"));
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 (!isNewRouter(u.pathname) && entry.lang) u.searchParams.set("lang", entry.lang);
else if (isBackendPath(u.pathname)) u.searchParams.delete("lang");
result = u.toString();
if (entry.cid && !(u.pathname === "/odoo" || u.pathname.startsWith("/odoo/"))) {
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);
});