forked from xifangczy/cat-catch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
background.js
689 lines (657 loc) · 26 KB
/
background.js
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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
importScripts("/js/init.js");
// Service Worker 5分钟后会强制终止扩展
// https://bugs.chromium.org/p/chromium/issues/detail?id=1271154
// https://stackoverflow.com/questions/66618136/persistent-service-worker-in-chrome-extension/70003493#70003493
chrome.webNavigation.onBeforeNavigate.addListener(function () { return; });
chrome.webNavigation.onHistoryStateUpdated.addListener(function () { return; });
chrome.runtime.onConnect.addListener(function (Port) {
if (Port.name !== "HeartBeat") return;
Port.postMessage("HeartBeat");
Port.onMessage.addListener(function (message, Port) { return; });
const interval = setInterval(function () {
clearInterval(interval);
Port.disconnect();
}, 250000);
Port.onDisconnect.addListener(function () {
if (interval) { clearInterval(interval); }
});
});
chrome.alarms.onAlarm.addListener(function (alarm) {
if (alarm.name === "nowClear" || alarm.name === "clear") {
clearRedundant();
return;
}
if (alarm.name === "save") {
(chrome.storage.session ?? chrome.storage.local).set({ MediaData: cacheData });
return;
}
});
// onBeforeRequest 浏览器发送请求之前使用正则匹配发送请求的URL
chrome.webRequest.onBeforeRequest.addListener(
function (data) {
try { findMedia(data, true); } catch (e) { console.log(e); }
}, { urls: ["<all_urls>"] }, ["requestBody"]
);
// 保存requestHeaders
chrome.webRequest.onSendHeaders.addListener(
function (data) {
if (G && !G.enable) { return; }
const requestHeaders = getRequestHeaders(data);
requestHeaders && G.requestHeaders.set(data.requestId, requestHeaders);
}, { urls: ["<all_urls>"] }, ['requestHeaders',
chrome.webRequest.OnBeforeSendHeadersOptions.EXTRA_HEADERS].filter(Boolean)
);
// onResponseStarted 浏览器接收到第一个字节触发,保证有更多信息判断资源类型
chrome.webRequest.onResponseStarted.addListener(
function (data) {
try {
const requestHeaders = G.requestHeaders.get(data.requestId);
if (requestHeaders) {
data.requestHeaders = requestHeaders;
G.requestHeaders.delete(data.requestId);
}
findMedia(data);
} catch (e) { console.log(e, data); }
}, { urls: ["<all_urls>"] }, ["responseHeaders"]
);
// 删除失败的requestHeadersData
chrome.webRequest.onErrorOccurred.addListener(
function (data) {
G.requestHeaders.delete(data.requestId);
G.blackList.delete(data.requestId);
}, { urls: ["<all_urls>"] }
);
function findMedia(data, isRegex = false, filter = false, timer = false) {
if (timer) { return; }
// Service Worker被强行杀死之后重新自我唤醒,等待全局变量初始化完成。
if (!G || !G.initSyncComplete || !G.initLocalComplete || G.tabId == undefined || cacheData.init) {
setTimeout(() => {
findMedia(data, isRegex, filter, true);
}, 233);
return;
}
if (!G.enable) { return; }
data.getTime = Date.now();
if (!isRegex && G.blackList.has(data.requestId)) {
G.blackList.delete(data.requestId);
return;
}
// 屏蔽特殊页面发起的资源
if (data.initiator != "null" &&
data.initiator != undefined &&
isSpecialPage(data.initiator)) { return; }
if (G.isFirefox &&
data.originUrl &&
isSpecialPage(data.originUrl)) { return; }
// 屏蔽特殊页面的资源
if (isSpecialPage(data.url)) { return; }
const urlParsing = new URL(data.url);
let [name, ext] = fileNameParse(urlParsing.pathname);
//正则匹配
if (isRegex && !filter) {
for (let key in G.Regex) {
if (!G.Regex[key].state) { continue; }
G.Regex[key].regex.lastIndex = 0;
let result = G.Regex[key].regex.exec(data.url);
if (result == null) { continue; }
if (G.Regex[key].blackList) {
G.blackList.add(data.requestId);
return;
}
data.extraExt = G.Regex[key].ext ? G.Regex[key].ext : undefined;
if (result.length == 1) {
findMedia(data, true, true);
return;
}
result.shift();
result = result.map(str => decodeURIComponent(str));
if (!result[0].startsWith('https://') && !result[0].startsWith('http://')) {
result[0] = urlParsing.protocol + "//" + data.url;
}
data.url = result.join("");
findMedia(data, true, true);
return;
}
return;
}
// 非正则匹配
if (!isRegex) {
// 获取头部信息
data.header = getResponseHeadersValue(data);
//检查后缀
if (!filter && ext != undefined) {
filter = CheckExtension(ext, data.header?.size);
if (filter == "break") { return; }
}
//检查类型
if (!filter && data.header?.type != undefined) {
filter = CheckType(data.header.type, data.header?.size);
if (filter == "break") { return; }
}
//查找附件
if (!filter && data.header?.attachment != undefined) {
const res = data.header.attachment.match(reFilename);
if (res && res[1]) {
[name, ext] = fileNameParse(decodeURIComponent(res[1]));
filter = CheckExtension(ext, 0);
if (filter == "break") { return; }
}
}
//放过类型为media的资源
if (data.type == "media") {
filter = true;
}
}
if (!filter) { return; }
// 谜之原因 获取得资源 tabId可能为 -1 firefox中则正常
// 检查是 -1 使用当前激活标签得tabID
data.tabId = data.tabId == -1 ? G.tabId : data.tabId;
cacheData[data.tabId] ??= [];
cacheData[G.tabId] ??= [];
// 查重 避免CPU占用 大于500 强制关闭查重
if (G.checkDuplicates && cacheData[data.tabId].length <= 500) {
for (let item of cacheData[data.tabId]) {
if (item.url.length == data.url.length &&
item.cacheURL.pathname == urlParsing.pathname &&
item.cacheURL.host == urlParsing.host &&
item.cacheURL.search == urlParsing.search) { return; }
}
}
chrome.tabs.get(data.tabId, async function (webInfo) {
if (chrome.runtime.lastError) { return; }
// requestHeaders 中cookie 单独列出来
if (data.requestHeaders?.cookie) {
data.cookie = data.requestHeaders.cookie;
data.requestHeaders.cookie = undefined;
}
const info = {
name: name,
url: data.url,
size: data.header?.size,
ext: ext,
type: data.mime ?? data.header?.type,
tabId: data.tabId,
isRegex: isRegex,
requestId: data.requestId ?? Date.now().toString(),
extraExt: data.extraExt,
initiator: data.initiator,
requestHeaders: data.requestHeaders,
cookie: data.cookie,
cacheURL: { host: urlParsing.host, search: urlParsing.search, pathname: urlParsing.pathname },
getTime: data.getTime
};
// 不存在 initiator 和 referer 使用web url代替initiator
if (info.initiator == undefined || info.initiator == "null") {
info.initiator = info.requestHeaders?.referer ?? webInfo?.url;
}
// 装载页面信息
info.title = webInfo?.title ?? "NULL";
info.favIconUrl = webInfo?.favIconUrl;
info.webUrl = webInfo?.url;
// 屏蔽资源
if (!isRegex && G.blackList.has(data.requestId)) {
G.blackList.delete(data.requestId);
return;
}
// 发送到popup 并检查自动下载
chrome.runtime.sendMessage(info, function () {
if (G.featAutoDownTabId.size > 0 && G.featAutoDownTabId.has(info.tabId)) {
const downDir = info.title == "NULL" ? "CatCatch/" : stringModify(info.title) + "/";
chrome.downloads.download({
url: info.url,
filename: downDir + info.name
});
}
if (G.send2local) {
try { send2local("catch", info, info.tabId); } catch (e) { console.log(e); }
}
if (chrome.runtime.lastError) { return; }
});
// 储存数据
cacheData[info.tabId] ??= [];
cacheData[info.tabId].push(info);
// 当前标签媒体数量大于100 开启防抖 等待5秒储存 或 积累10个资源储存一次。
if (cacheData[info.tabId].length >= 100 && debounceCount <= 10) {
debounceCount++;
clearTimeout(debounce);
debounce = setTimeout(function () { save(info.tabId); }, 5000);
return;
}
// 时间间隔小于500毫秒 等待2秒储存
if (Date.now() - debounceTime <= 500) {
clearTimeout(debounce);
debounceTime = Date.now();
debounce = setTimeout(function () { save(info.tabId); }, 2000);
return;
}
save(info.tabId);
});
}
// cacheData数据 储存到 chrome.storage.local
function save(tabId) {
clearTimeout(debounce);
debounceTime = Date.now();
debounceCount = 0;
(chrome.storage.session ?? chrome.storage.local).set({ MediaData: cacheData }, function () {
chrome.runtime.lastError && console.log(chrome.runtime.lastError);
});
cacheData[tabId] && SetIcon({ number: cacheData[tabId].length, tabId: tabId });
}
// 监听来自popup 和 options的请求
chrome.runtime.onMessage.addListener(function (Message, sender, sendResponse) {
if (!G.initLocalComplete || !G.initSyncComplete) {
sendResponse("error");
return true;
}
if (Message.Message == "pushData") {
(chrome.storage.session ?? chrome.storage.local).set({ MediaData: cacheData });
sendResponse("ok");
return true;
}
if (Message.Message == "getAllData") {
sendResponse(cacheData);
return true;
}
// 图标设置
if (Message.Message == "ClearIcon") {
if (Message.type) {
if (Message.tabId) {
SetIcon({ tabId: Message.tabId });
} else if (G.tabId) {
SetIcon({ tabId: G.tabId });
}
} else {
SetIcon({ tips: false });
}
sendResponse("ok");
return true;
}
if (Message.Message == "enable") {
G.enable = !G.enable;
chrome.storage.sync.set({ enable: G.enable });
chrome.action.setIcon({ path: G.enable ? "/img/icon.png" : "/img/icon-disable.png" });
sendResponse(G.enable);
return true;
}
Message.tabId = Message.tabId ?? G.tabId;
if (Message.Message == "getData") {
sendResponse(cacheData[Message.tabId]);
return true;
}
if (Message.Message == "getButtonState") {
let state = {
MobileUserAgent: G.featMobileTabId.has(Message.tabId),
AutoDown: G.featAutoDownTabId.has(Message.tabId),
enable: G.enable,
}
G.scriptList.forEach(function (item, key) {
state[item.key] = item.tabId.has(Message.tabId);
});
sendResponse(state);
return true;
}
// 模拟手机
if (Message.Message == "mobileUserAgent") {
mobileUserAgent(Message.tabId, !G.featMobileTabId.has(Message.tabId));
chrome.tabs.reload(Message.tabId, { bypassCache: true });
sendResponse("ok");
return true;
}
// 自动下载
if (Message.Message == "autoDown") {
if (G.featAutoDownTabId.has(Message.tabId)) {
G.featAutoDownTabId.delete(Message.tabId);
} else {
G.featAutoDownTabId.add(Message.tabId);
}
(chrome.storage.session ?? chrome.storage.local).set({ featAutoDownTabId: Array.from(G.featAutoDownTabId) });
sendResponse("ok");
return true;
}
// 脚本
if (Message.Message == "script") {
if (!G.scriptList.has(Message.script)) {
sendResponse("error no exists");
return false;
}
const script = G.scriptList.get(Message.script);
const scriptTabid = script.tabId;
const refresh = Message.refresh ?? script.refresh;
if (scriptTabid.has(Message.tabId)) {
scriptTabid.delete(Message.tabId);
refresh && chrome.tabs.reload(Message.tabId, { bypassCache: true });
sendResponse("ok");
return true;
}
scriptTabid.add(Message.tabId);
if (refresh) {
chrome.tabs.reload(Message.tabId, { bypassCache: true });
} else {
script.i18n && chrome.scripting.executeScript({
target: { tabId: Message.tabId, allFrames: script.allFrames },
files: ["catch-script/i18n.js"],
injectImmediately: true,
world: "MAIN"
});
chrome.scripting.executeScript({
target: { tabId: Message.tabId, allFrames: script.allFrames },
files: ["catch-script/" + Message.script],
injectImmediately: true,
world: script.world
});
}
sendResponse("ok");
return true;
}
if (Message.Message == "scriptI18n") {
chrome.scripting.executeScript({
target: { tabId: Message.tabId, allFrames: true },
files: ["catch-script/i18n.js"],
injectImmediately: true,
world: "MAIN"
});
sendResponse("ok");
return true;
}
// Heart Beat
if (Message.Message == "HeartBeat") {
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
if (tabs[0] && tabs[0].id) {
G.tabId = tabs[0].id;
}
});
sendResponse("HeartBeat OK");
return true;
}
// 清理数据
if (Message.Message == "clearData") {
// 当前标签
if (Message.type) {
delete cacheData[Message.tabId];
(chrome.storage.session ?? chrome.storage.local).set({ MediaData: cacheData });
clearRedundant();
sendResponse("OK");
return true;
}
// 其他标签
for (let item in cacheData) {
if (item == Message.tabId) { continue; }
delete cacheData[item];
}
(chrome.storage.session ?? chrome.storage.local).set({ MediaData: cacheData });
clearRedundant();
sendResponse("OK");
return true;
}
// 清理冗余数据
if (Message.Message == "clearRedundant") {
clearRedundant();
sendResponse("OK");
return true;
}
// 从 content-script 或 catch-script 传来的媒体url
if (Message.Message == "addMedia") {
chrome.tabs.query({}, function (tabs) {
for (let item of tabs) {
if (item.url == Message.href) {
findMedia({ url: Message.url, tabId: item.id, extraExt: Message.extraExt, mime: Message.mime, requestId: Message.requestId, requestHeaders: Message.requestHeaders }, true, true);
return true;
}
}
findMedia({ url: Message.url, tabId: -1, extraExt: Message.extraExt, mime: Message.mime, requestId: Message.requestId, initiator: Message.href, requestHeaders: Message.requestHeaders }, true, true);
});
sendResponse("ok");
return true;
}
// ffmpeg网页通信
if (Message.Message == "catCatchFFmpeg") {
const data = { ...Message, Message: "ffmpeg", tabId: Message.tabId ?? sender.tab.id, version: G.ffmpegConfig.version };
chrome.tabs.query({ url: G.ffmpegConfig.url }, function (tabs) {
if (chrome.runtime.lastError || !tabs.length) {
chrome.tabs.create({ url: G.ffmpegConfig.url, active: Message.active ?? true }, function (tab) {
G.ffmpegConfig.tab = tab.id;
G.ffmpegConfig.data = data;
});
return true;
}
chrome.tabs.sendMessage(tabs[0].id, data);
});
sendResponse("ok");
return true;
}
// 发送数据到本地
if (Message.Message == "send2local" && G.send2local) {
try { send2local(Message.action, Message.data, Message.tabId); } catch (e) { console.log(e); }
sendResponse("ok");
return true;
}
sendResponse("Error");
return true;
});
// 选定标签 更新G.tabId
chrome.tabs.onHighlighted.addListener(function (activeInfo) {
if (!activeInfo.tabId || activeInfo.tabId == -1) { return; }
G.tabId = activeInfo.tabId;
});
// 切换标签,更新全局变量G.tabId 更新图标
chrome.tabs.onActivated.addListener(function (activeInfo) {
G.tabId = activeInfo.tabId;
if (cacheData[G.tabId] !== undefined) {
SetIcon({ number: cacheData[G.tabId].length, tabId: G.tabId });
return;
}
SetIcon({ tabId: G.tabId });
});
// 切换窗口,更新全局变量G.tabId
chrome.windows.onFocusChanged.addListener(function (activeInfo) {
if (!activeInfo.tabId || activeInfo.tabId == -1) { return; }
G.tabId = activeInfo.tabId;
}, { filters: ["normal"] });
// 标签更新 清理数据
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
if (isSpecialPage(tab.url) || tabId <= 0 || !G.initSyncComplete) { return; }
if (changeInfo.status && changeInfo.status == "loading" && G.autoClearMode == 2) {
chrome.alarms.get("save", function (alarm) {
if (!alarm) {
delete cacheData[tabId];
SetIcon({ tabId: tabId });
chrome.alarms.create("save", { when: Date.now() + 1000 });
}
});
}
});
// 载入frame时
chrome.webNavigation.onCommitted.addListener(function (details) {
// console.log(details);
if (isSpecialPage(details.url) || details.tabId <= 0 || !G.initSyncComplete) { return; }
// 刷新清理角标数
if (details.frameId == 0 && (details.transitionType == "reload" || details.transitionType == "link") && G.autoClearMode == 1) {
delete cacheData[details.tabId];
(chrome.storage.session ?? chrome.storage.local).set({ MediaData: cacheData });
SetIcon({ tabId: details.tabId });
}
// chrome内核版本 102 以下不支持 chrome.scripting.executeScript API
if (G.version < 102) { return; }
// catch-script 脚本
G.scriptList.forEach(function (item, script) {
if (!item.tabId.has(details.tabId) || !item.allFrames) { return true; }
item.i18n && chrome.scripting.executeScript({
target: { tabId: details.tabId, frameIds: [details.frameId] },
files: ["catch-script/i18n.js"],
injectImmediately: true,
world: "MAIN"
});
chrome.scripting.executeScript({
target: { tabId: details.tabId, frameIds: [details.frameId] },
files: [`catch-script/${script}`],
injectImmediately: true,
world: item.world
});
});
// 模拟手机
if (G.initLocalComplete && G.featMobileTabId.size > 0 && G.featMobileTabId.has(details.tabId)) {
chrome.scripting.executeScript({
args: [G.MobileUserAgent.toString()],
target: { tabId: details.tabId, frameIds: [details.frameId] },
func: function () {
Object.defineProperty(navigator, 'userAgent', { value: arguments[0], writable: false });
},
injectImmediately: true,
world: "MAIN"
});
}
});
// 标签关闭 清除数据
chrome.tabs.onRemoved.addListener(function (tabId) {
// 清理缓存数据
chrome.alarms.get("nowClear", function (alarm) {
!alarm && chrome.alarms.create("nowClear", { when: Date.now() + 1000 });
});
});
// 快捷键
chrome.commands.onCommand.addListener(function (command) {
if (command == "auto_down") {
if (G.featAutoDownTabId.has(G.tabId)) {
G.featAutoDownTabId.delete(G.tabId);
} else {
G.featAutoDownTabId.add(G.tabId);
}
(chrome.storage.session ?? chrome.storage.local).set({ featAutoDownTabId: Array.from(G.featAutoDownTabId) });
} else if (command == "catch") {
const scriptTabid = G.scriptList.get("catch.js").tabId;
scriptTabid.has(G.tabId) ? scriptTabid.delete(G.tabId) : scriptTabid.add(G.tabId);
chrome.tabs.reload(G.tabId, { bypassCache: true });
} else if (command == "m3u8") {
chrome.tabs.create({ url: "m3u8.html" });
} else if (command == "clear") {
delete cacheData[G.tabId];
(chrome.storage.session ?? chrome.storage.local).set({ MediaData: cacheData });
clearRedundant();
SetIcon({ tabId: G.tabId });
} else if (command == "enable") {
G.enable = !G.enable;
chrome.storage.sync.set({ enable: G.enable });
chrome.action.setIcon({ path: G.enable ? "/img/icon.png" : "/img/icon-disable.png" });
}
});
chrome.webNavigation.onCompleted.addListener(function (details) {
if (G.ffmpegConfig.tab && details.tabId == G.ffmpegConfig.tab) {
setTimeout(() => {
chrome.tabs.sendMessage(details.tabId, G.ffmpegConfig.data);
G.ffmpegConfig.data = undefined;
G.ffmpegConfig.tab = 0;
}, 500);
}
});
//检查扩展名以及大小限制
function CheckExtension(ext, size) {
const Ext = G.Ext.get(ext);
if (!Ext) { return false; }
if (!Ext.state) { return "break"; }
if (Ext.size != 0 && size != undefined && size <= Ext.size * 1024) { return "break"; }
return true;
}
//检查类型以及大小限制
function CheckType(dataType, dataSize) {
const typeInfo = G.Type.get(dataType.split("/")[0] + "/*") || G.Type.get(dataType);
if (!typeInfo) { return false; }
if (!typeInfo.state) { return "break"; }
if (typeInfo.size != 0 && dataSize != undefined && dataSize <= typeInfo.size * 1024) { return "break"; }
return true;
}
// 获取文件名 后缀
function fileNameParse(pathname) {
let fileName = decodeURI(pathname.split("/").pop());
let ext = fileName.split(".");
ext = ext.length == 1 ? undefined : ext.pop().toLowerCase();
return [fileName, ext ? ext : undefined];
}
//获取Header属性的值
function getResponseHeadersValue(data) {
const header = {};
if (data.responseHeaders == undefined || data.responseHeaders.length == 0) { return header; }
for (let item of data.responseHeaders) {
item.name = item.name.toLowerCase();
if (item.name == "content-length") {
header.size ??= parseInt(item.value);
} else if (item.name == "content-type") {
header.type = item.value.split(";")[0].toLowerCase();
} else if (item.name == "content-disposition") {
header.attachment = item.value;
} else if (item.name == "content-range") {
let size = item.value.split('/')[1];
if (size !== '*') {
header.size = parseInt(size);
}
}
}
return header;
}
function getRequestHeaders(data) {
if (data.requestHeaders == undefined || data.requestHeaders.length == 0) { return false; }
const header = {};
for (let item of data.requestHeaders) {
item.name = item.name.toLowerCase();
if (item.name == "referer") {
header.referer = item.value.toLowerCase();
} else if (item.name == "origin") {
header.origin = item.value.toLowerCase();
} else if (item.name == "cookie") {
header.cookie = item.value.toLowerCase();
}
}
if (Object.keys(header).length) {
return header;
}
return false;
}
//设置扩展图标
function SetIcon(obj) {
if (obj.number == 0 || obj.number == undefined) {
chrome.action.setBadgeText({ text: "", tabId: obj.tabId }, function () { if (chrome.runtime.lastError) { return; } });
// chrome.action.setTitle({ title: "还没闻到味儿~", tabId: obj.tabId }, function () { if (chrome.runtime.lastError) { return; } });
} else if (G.badgeNumber) {
obj.number = obj.number > 999 ? "999+" : obj.number.toString();
chrome.action.setBadgeText({ text: obj.number, tabId: obj.tabId }, function () { if (chrome.runtime.lastError) { return; } });
// chrome.action.setTitle({ title: "抓到 " + obj.number + " 条鱼", tabId: obj.tabId }, function () { if (chrome.runtime.lastError) { return; } });
}
}
// 模拟手机端
function mobileUserAgent(tabId, change = false) {
if (change) {
G.featMobileTabId.add(tabId);
(chrome.storage.session ?? chrome.storage.local).set({ featMobileTabId: Array.from(G.featMobileTabId) });
chrome.declarativeNetRequest.updateSessionRules({
removeRuleIds: [tabId],
addRules: [{
"id": tabId,
"action": {
"type": "modifyHeaders",
"requestHeaders": [{
"header": "User-Agent",
"operation": "set",
"value": G.MobileUserAgent
}]
},
"condition": {
"tabIds": [tabId],
"resourceTypes": Object.values(chrome.declarativeNetRequest.ResourceType)
}
}]
});
return true;
}
G.featMobileTabId.delete(tabId) && (chrome.storage.session ?? chrome.storage.local).set({ featMobileTabId: Array.from(G.featMobileTabId) });
chrome.declarativeNetRequest.updateSessionRules({
removeRuleIds: [tabId]
});
}
// 判断特殊页面
function isSpecialPage(url) {
if (!url || url == "null") { return true; }
return !(url.startsWith("http://") || url.startsWith("https://") || url.startsWith("blob:"));
}
// 测试
// chrome.storage.local.get(function (data) { console.log(data.MediaData) });
// chrome.declarativeNetRequest.getSessionRules(function (rules) { console.log(rules); });
// chrome.tabs.query({}, function (tabs) { for (let item of tabs) { console.log(item.id); } });