-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathbackground.js
More file actions
290 lines (259 loc) · 9.39 KB
/
Copy pathbackground.js
File metadata and controls
290 lines (259 loc) · 9.39 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
const DEFAULT_TIMEOUT_MIN = 5;
const CHECK_INTERVAL_MIN = 1;
// { tabId: lastActiveTimestamp }
const tabActivity = {};
// Record activity for a tab
function markActive(tabId) {
tabActivity[tabId] = Date.now();
}
// On tab activated (user switches to it)
chrome.tabs.onActivated.addListener(({ tabId }) => {
markActive(tabId);
});
// On tab updated (page load, navigation)
chrome.tabs.onUpdated.addListener((tabId, changeInfo) => {
if (changeInfo.status === "complete" || changeInfo.url) {
markActive(tabId);
}
});
// On tab created
chrome.tabs.onCreated.addListener((tab) => {
markActive(tab.id);
});
// On tab removed, clean up
chrome.tabs.onRemoved.addListener((tabId) => {
delete tabActivity[tabId];
});
// Initialize: mark all existing tabs as active now
chrome.tabs.query({}, (tabs) => {
for (const tab of tabs) {
markActive(tab.id);
}
});
// Periodic cleanup check
chrome.alarms.create("tabCleanup", { periodInMinutes: CHECK_INTERVAL_MIN });
chrome.alarms.onAlarm.addListener(async (alarm) => {
if (alarm.name !== "tabCleanup") return;
const { exclusions = [], enabled = true, timeoutMin = DEFAULT_TIMEOUT_MIN } =
await chrome.storage.local.get(["exclusions", "enabled", "timeoutMin"]);
if (!enabled) return;
const now = Date.now();
const timeoutMs = timeoutMin * 60 * 1000;
const tabs = await chrome.tabs.query({});
// Never close the last tab in a window
const windowTabCounts = {};
for (const tab of tabs) {
windowTabCounts[tab.windowId] = (windowTabCounts[tab.windowId] || 0) + 1;
}
// Find the currently active tab so we never close it
const activeTabs = new Set();
const windows = await chrome.windows.getAll();
for (const win of windows) {
const [active] = await chrome.tabs.query({
active: true,
windowId: win.id,
});
if (active) activeTabs.add(active.id);
}
for (const tab of tabs) {
// Skip active tabs
if (activeTabs.has(tab.id)) {
markActive(tab.id);
continue;
}
// Skip pinned tabs
if (tab.pinned) continue;
// Skip if it's the last tab in its window
if (windowTabCounts[tab.windowId] <= 1) continue;
// Skip excluded hosts
if (tab.url) {
try {
const host = new URL(tab.url).hostname;
if (
exclusions.some(
(ex) => host === ex || host.endsWith("." + ex)
)
) {
continue;
}
} catch {}
}
// Check inactivity
const lastActive = tabActivity[tab.id] || 0;
if (now - lastActive >= timeoutMs) {
windowTabCounts[tab.windowId]--;
// Save to closed history before removing
saveClosedTab(tab);
chrome.tabs.remove(tab.id);
delete tabActivity[tab.id];
}
}
});
// Save closed tab to history
function saveClosedTab(tab) {
if (!tab.url || tab.url.startsWith("chrome://")) return;
chrome.storage.local.get(["closed_tabs"], (data) => {
const closed = data.closed_tabs || [];
closed.unshift({
url: tab.url,
title: tab.title || tab.url,
favIconUrl: tab.favIconUrl || "",
time: Date.now(),
});
if (closed.length > 50) closed.length = 50;
chrome.storage.local.set({ closed_tabs: closed });
});
}
// ═══════════════════════════════════
// Redirect Tracer
// ═══════════════════════════════════
// { tabId: { chain: [{url, statusCode, statusLine}], finalUrl, finalStatus } }
const redirectData = {};
// When a new main-frame navigation starts, reset the chain
chrome.webNavigation.onBeforeNavigate.addListener((details) => {
if (details.frameId !== 0) return;
redirectData[details.tabId] = { chain: [], finalUrl: null, finalStatus: null };
});
// Capture each redirect hop
chrome.webRequest.onBeforeRedirect.addListener(
(details) => {
if (details.type !== "main_frame") return;
if (!redirectData[details.tabId]) {
redirectData[details.tabId] = { chain: [], finalUrl: null, finalStatus: null };
}
redirectData[details.tabId].chain.push({
url: details.url,
statusCode: details.statusCode,
statusLine: details.statusLine || "",
redirectUrl: details.redirectUrl,
});
},
{ urls: ["<all_urls>"] }
);
// Capture final completed request
chrome.webRequest.onCompleted.addListener(
(details) => {
if (details.type !== "main_frame") return;
if (!redirectData[details.tabId]) {
redirectData[details.tabId] = { chain: [], finalUrl: null, finalStatus: null };
}
redirectData[details.tabId].finalUrl = details.url;
redirectData[details.tabId].finalStatus = details.statusCode;
},
{ urls: ["<all_urls>"] }
);
// Clean up on tab close
chrome.tabs.onRemoved.addListener((tabId) => {
delete redirectData[tabId];
});
// Respond to popup requests
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
if (msg.type === "getRedirects") {
sendResponse(redirectData[msg.tabId] || { chain: [], finalUrl: null, finalStatus: null });
}
if (msg.type === "pip") {
chrome.scripting.executeScript({
target: { tabId: msg.tabId },
func: () => {
if (document.pictureInPictureElement) {
document.exitPictureInPicture();
return { action: "exited" };
}
const videos = Array.from(document.querySelectorAll("video"));
if (!videos.length) return { error: "No video found on this page" };
const playing = videos.filter(v => !v.paused && !v.ended);
let video;
if (playing.length) {
video = playing.reduce((a, b) =>
(b.videoWidth * b.videoHeight) > (a.videoWidth * a.videoHeight) ? b : a
);
} else {
video = videos.reduce((a, b) =>
(b.videoWidth * b.videoHeight) > (a.videoWidth * a.videoHeight) ? b : a
);
}
const enterPip = () => video.requestPictureInPicture()
.then(() => ({ action: "entered" }))
.catch(e => ({ error: e.message }));
// requestPictureInPicture() throws if metadata isn't loaded yet
// (readyState 0 = HAVE_NOTHING). Wait for it, then retry.
if (video.readyState === 0) {
return new Promise((resolve) => {
const onReady = () => {
cleanup();
resolve(enterPip());
};
const onError = () => {
cleanup();
resolve({ error: "Video failed to load" });
};
const timer = setTimeout(() => {
cleanup();
resolve({ error: "Video metadata did not load in time" });
}, 5000);
const cleanup = () => {
clearTimeout(timer);
video.removeEventListener("loadedmetadata", onReady);
video.removeEventListener("error", onError);
};
video.addEventListener("loadedmetadata", onReady, { once: true });
video.addEventListener("error", onError, { once: true });
// Nudge the browser to start loading metadata if it hasn't.
if (video.preload === "none") video.preload = "metadata";
video.load();
});
}
return enterPip();
},
}).then(results => {
sendResponse(results[0]?.result || { error: "No result" });
}).catch(err => {
sendResponse({ error: err.message });
});
return true; // async sendResponse
}
});
// Set defaults on install
chrome.runtime.onInstalled.addListener(() => {
chrome.storage.local.get(["enabled", "timeoutMin", "exclusions"], (data) => {
const defaults = {};
if (data.enabled === undefined) defaults.enabled = true;
if (data.timeoutMin === undefined) defaults.timeoutMin = DEFAULT_TIMEOUT_MIN;
if (data.exclusions === undefined) defaults.exclusions = [];
if (Object.keys(defaults).length) {
chrome.storage.local.set(defaults);
}
});
});
// ═══════════════════════════════════
// Photopea No Ads — MAIN-world script registration
// (must run in the page world before Photopea's own scripts)
// ═══════════════════════════════════
const PHOTOPEA_SCRIPT_ID = "sl-photopea-main";
let photopeaSyncChain = Promise.resolve();
function syncPhotopeaScript() {
// Serialize so a toggle during startup can't race the initial registration
photopeaSyncChain = photopeaSyncChain.then(doSyncPhotopeaScript).catch(() => {});
return photopeaSyncChain;
}
async function doSyncPhotopeaScript() {
const { photopea_enabled } = await chrome.storage.local.get(["photopea_enabled"]);
const enabled = photopea_enabled !== false;
const existing = await chrome.scripting.getRegisteredContentScripts({ ids: [PHOTOPEA_SCRIPT_ID] });
if (enabled && existing.length === 0) {
await chrome.scripting.registerContentScripts([{
id: PHOTOPEA_SCRIPT_ID,
matches: ["*://www.photopea.com/*", "*://photopea.com/*"],
js: ["photopea-main.js"],
runAt: "document_start",
world: "MAIN",
}]).catch(() => {});
} else if (!enabled && existing.length > 0) {
await chrome.scripting.unregisterContentScripts({ ids: [PHOTOPEA_SCRIPT_ID] }).catch(() => {});
}
}
syncPhotopeaScript();
chrome.runtime.onInstalled.addListener(syncPhotopeaScript);
chrome.storage.onChanged.addListener((changes, area) => {
if (area === "local" && changes.photopea_enabled) syncPhotopeaScript();
});