-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
90 lines (77 loc) · 3.02 KB
/
background.js
File metadata and controls
90 lines (77 loc) · 3.02 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
/**
* TubeSnap - Background Script
*/
'use strict';
// ===== 安装事件 =====
chrome.runtime.onInstalled.addListener((details) => {
if (details.reason === 'install') {
// 首次安装,设置默认配置
chrome.storage.sync.set({
screenshotFormat: 'png',
screenshotQuality: 95,
screenshotAction: 'both',
enableWatermark: false,
watermarkPosition: 'bottom-right',
watermarkStyle: 'simple',
});
console.log('TubeSnap 已安装');
}
});
// ===== 处理下载请求 =====
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === 'download') {
chrome.downloads.download({
url: request.url,
filename: request.filename,
saveAs: false
}, (downloadId) => {
if (chrome.runtime.lastError) {
console.error('下载失败:', chrome.runtime.lastError);
sendResponse({ success: false, error: chrome.runtime.lastError.message });
} else {
sendResponse({ success: true, downloadId });
}
});
return true; // 保持消息通道开放以进行异步响应
}
// popup 触发截图:等待 popup 关闭后再发消息,提升 clipboard 成功率
if (request.action === 'take-screenshot-from-popup') {
const tabId = request.tabId;
const sendCapture = () => new Promise((resolve) => {
chrome.tabs.sendMessage(tabId, { action: 'take-screenshot' }, (resp) => {
const err = chrome.runtime.lastError;
if (err) {
resolve({ ok: false, error: err.message });
return;
}
resolve({ ok: true, resp });
});
});
(async () => {
await new Promise(r => setTimeout(r, 220));
let result = await sendCapture();
if (!result.ok && /Receiving end does not exist/i.test(result.error || '')) {
// content script 可能尚未注入(例如刚更新扩展后未刷新页面)
try {
await chrome.scripting.insertCSS({ target: { tabId }, files: ['content.css'] });
} catch (_) {}
try {
await chrome.scripting.executeScript({ target: { tabId }, files: ['content.js'] });
} catch (e) {
sendResponse({ success: false, error: e?.message || result.error || 'Injection failed' });
return;
}
await new Promise(r => setTimeout(r, 80));
result = await sendCapture();
}
if (!result.ok) {
sendResponse({ success: false, error: result.error || 'Unknown error' });
return;
}
sendResponse({ success: true });
})();
return true;
}
return false;
});
console.log('TubeSnap background script loaded');