-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
381 lines (323 loc) · 8.92 KB
/
content.js
File metadata and controls
381 lines (323 loc) · 8.92 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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
/**
* Volume Normalizer - Content Script
* Automatically normalizes video/audio volume on configured sites.
*/
const PROCESSED_ATTR = "data-volume-normalized";
const MEDIA_SELECTOR = "video, audio";
const VOLUME_EPSILON = 0.01;
const FALLBACK_RESCAN_MS = 5000;
const DEBUG = false;
// Site configuration - maps site IDs to domain patterns
const SITE_DOMAINS = {
x: ["twitter.com", "x.com"],
tiktok: ["tiktok.com"],
instagram: ["instagram.com"],
facebook: ["facebook.com"],
youtube: ["youtube.com"],
twitch: ["twitch.tv"],
reddit: ["reddit.com"],
dailymotion: ["dailymotion.com"],
vimeo: ["vimeo.com"],
snapchat: ["snapchat.com"],
pinterest: ["pinterest.com"],
tumblr: ["tumblr.com"],
linkedin: ["linkedin.com"]
};
// Default settings
const DEFAULT_SETTINGS = {
volume: 25,
enabledSites: Object.keys(SITE_DOMAINS).reduce((acc, siteId) => {
acc[siteId] = true;
return acc;
}, {})
};
// Current settings (loaded from storage)
let currentSettings = { ...DEFAULT_SETTINGS };
const currentSiteId = getCurrentSiteId(window.location.hostname);
const attachedMedia = new WeakSet();
const internalVolumeSet = new WeakMap();
let pendingNodes = new Set();
let flushTimerId = null;
let idleScanTimerId = null;
function debugLog(...args) {
if (DEBUG) {
console.debug("[Volume Normalizer]", ...args);
}
}
function clampVolume(rawValue) {
const numberValue = Number(rawValue);
if (!Number.isFinite(numberValue)) {
return DEFAULT_SETTINGS.volume;
}
return Math.max(0, Math.min(100, Math.round(numberValue)));
}
function sanitizeEnabledSites(rawEnabledSites) {
const enabledSites = {};
const source =
rawEnabledSites && typeof rawEnabledSites === "object" ? rawEnabledSites : {};
for (const siteId of Object.keys(SITE_DOMAINS)) {
enabledSites[siteId] = source[siteId] !== false;
}
return enabledSites;
}
function sanitizeSettings(rawSettings) {
const settings = rawSettings && typeof rawSettings === "object" ? rawSettings : {};
return {
volume: clampVolume(settings.volume),
enabledSites: sanitizeEnabledSites(settings.enabledSites)
};
}
/**
* Match only exact domains or subdomains.
*/
function hostnameMatchesDomain(hostname, domain) {
const normalizedHostname = hostname.toLowerCase();
const normalizedDomain = domain.toLowerCase();
return (
normalizedHostname === normalizedDomain ||
normalizedHostname.endsWith(`.${normalizedDomain}`)
);
}
/**
* Get the current site ID based on hostname.
*/
function getCurrentSiteId(hostname) {
for (const [siteId, domains] of Object.entries(SITE_DOMAINS)) {
if (domains.some((domain) => hostnameMatchesDomain(hostname, domain))) {
return siteId;
}
}
return null;
}
/**
* Check if the current site is enabled.
*/
function isSiteEnabled() {
if (!currentSiteId) {
return false;
}
return currentSettings.enabledSites[currentSiteId] !== false;
}
/**
* Get target volume (0-1 scale).
*/
function getTargetVolume() {
return currentSettings.volume / 100;
}
function shouldUpdateVolume(element, targetVolume) {
return Math.abs(element.volume - targetVolume) > VOLUME_EPSILON;
}
function setVolumeSafely(element, targetVolume) {
if (!shouldUpdateVolume(element, targetVolume) || internalVolumeSet.get(element)) {
return;
}
internalVolumeSet.set(element, true);
try {
element.volume = targetVolume;
} catch (error) {
debugLog("Failed to set volume on element:", error);
} finally {
internalVolumeSet.set(element, false);
}
}
function attachMediaListeners(element) {
if (attachedMedia.has(element)) {
return;
}
const reapplyVolume = () => {
if (!isSiteEnabled()) {
return;
}
setVolumeSafely(element, getTargetVolume());
element.setAttribute(PROCESSED_ATTR, String(currentSettings.volume));
};
element.addEventListener("volumechange", () => {
if (internalVolumeSet.get(element)) {
return;
}
reapplyVolume();
});
element.addEventListener("play", reapplyVolume);
element.addEventListener("loadeddata", reapplyVolume);
attachedMedia.add(element);
}
/**
* Normalize volume on one media element.
*/
function normalizeMediaElement(
element,
targetVolume = getTargetVolume(),
volumeAttribute = String(currentSettings.volume)
) {
if (!(element instanceof HTMLMediaElement) || !isSiteEnabled()) {
return;
}
attachMediaListeners(element);
setVolumeSafely(element, targetVolume);
element.setAttribute(PROCESSED_ATTR, volumeAttribute);
}
function normalizeMediaNode(node) {
if (!(node instanceof Element)) {
return;
}
const targetVolume = getTargetVolume();
const volumeAttribute = String(currentSettings.volume);
if (node.matches(MEDIA_SELECTOR)) {
normalizeMediaElement(node, targetVolume, volumeAttribute);
}
node.querySelectorAll(MEDIA_SELECTOR).forEach((mediaElement) => {
normalizeMediaElement(mediaElement, targetVolume, volumeAttribute);
});
}
function nodeContainsMedia(node) {
return (
node instanceof Element &&
(node.matches(MEDIA_SELECTOR) || node.querySelector(MEDIA_SELECTOR) !== null)
);
}
/**
* Find and normalize all media elements on the page.
*/
function normalizeAllMedia() {
if (!isSiteEnabled()) {
return;
}
const targetVolume = getTargetVolume();
const volumeAttribute = String(currentSettings.volume);
document.querySelectorAll(MEDIA_SELECTOR).forEach((mediaElement) => {
const lastVolume = mediaElement.getAttribute(PROCESSED_ATTR);
if (
lastVolume !== volumeAttribute ||
shouldUpdateVolume(mediaElement, targetVolume)
) {
normalizeMediaElement(mediaElement, targetVolume, volumeAttribute);
} else {
attachMediaListeners(mediaElement);
}
});
}
function flushPendingNodes() {
flushTimerId = null;
if (!isSiteEnabled()) {
pendingNodes.clear();
return;
}
for (const node of pendingNodes) {
normalizeMediaNode(node);
}
pendingNodes.clear();
}
function scheduleNodeNormalization(node) {
if (!nodeContainsMedia(node)) {
return;
}
pendingNodes.add(node);
if (flushTimerId !== null) {
return;
}
flushTimerId = window.setTimeout(flushPendingNodes, 60);
}
function scheduleIdleMediaScan() {
if (idleScanTimerId !== null) {
return;
}
const runScan = () => {
idleScanTimerId = null;
if (document.visibilityState === "visible" && isSiteEnabled()) {
normalizeAllMedia();
}
};
if ("requestIdleCallback" in window) {
idleScanTimerId = window.requestIdleCallback(runScan, { timeout: 1000 });
return;
}
idleScanTimerId = window.setTimeout(runScan, 250);
}
/**
* Set up MutationObserver to catch dynamically added media.
*/
function setupObserver() {
const observer = new MutationObserver((mutations) => {
for (const mutation of mutations) {
if (mutation.type === "childList") {
mutation.addedNodes.forEach((addedNode) => {
if (addedNode.nodeType === Node.ELEMENT_NODE) {
scheduleNodeNormalization(addedNode);
}
});
}
if (
mutation.type === "attributes" &&
mutation.target instanceof HTMLMediaElement
) {
mutation.target.removeAttribute(PROCESSED_ATTR);
scheduleNodeNormalization(mutation.target);
}
}
});
observer.observe(document.documentElement, {
childList: true,
subtree: true,
attributes: true,
attributeFilter: ["src"]
});
}
function loadSettings() {
return new Promise((resolve) => {
chrome.storage.sync.get(DEFAULT_SETTINGS, (settings) => {
if (chrome.runtime.lastError) {
debugLog("Failed to load settings:", chrome.runtime.lastError.message);
currentSettings = {
volume: DEFAULT_SETTINGS.volume,
enabledSites: { ...DEFAULT_SETTINGS.enabledSites }
};
resolve();
return;
}
currentSettings = sanitizeSettings(settings);
resolve();
});
});
}
/**
* Listen for settings changes.
*/
function setupSettingsListener() {
chrome.storage.onChanged.addListener((changes, namespace) => {
if (namespace !== "sync") {
return;
}
const nextSettings = { ...currentSettings };
if (changes.volume) {
nextSettings.volume = clampVolume(changes.volume.newValue);
}
if (changes.enabledSites) {
nextSettings.enabledSites = sanitizeEnabledSites(changes.enabledSites.newValue);
}
currentSettings = nextSettings;
normalizeAllMedia();
});
}
/**
* Initialize content script.
*/
async function init() {
if (!currentSiteId) {
debugLog("Site not supported for hostname:", window.location.hostname);
return;
}
await loadSettings();
setupSettingsListener();
setupObserver();
normalizeAllMedia();
// Low-frequency fallback for websites that bypass events/observers.
window.setInterval(() => {
scheduleIdleMediaScan();
}, FALLBACK_RESCAN_MS);
debugLog(`Initialized for ${currentSiteId}`);
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", init);
} else {
init();
}