-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpopup.js
More file actions
286 lines (245 loc) · 10.5 KB
/
Copy pathpopup.js
File metadata and controls
286 lines (245 loc) · 10.5 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
/**
* Popup Script — SourceMap Extractor v5
*
* URL 收集: content script 优先(performance.getEntriesByType),background webRequest 兜底
* .map 检测: background 负责 fetch(无 CORS)
* 下载: fire-and-forget + 进度消息
*/
'use strict';
const state = { scanResult: null, isScanning: false, isDownloading: false };
const $ = (id) => document.getElementById(id);
const statusDot = $('statusDot');
const statusText = $('statusText');
const urlPreview = $('urlPreview');
const btnScan = $('btnScan');
const btnDownloadMaps = $('btnDownloadMaps');
const btnDownloadAll = $('btnDownloadAll');
const progressContainer = $('progressContainer');
const progressFill = $('progressFill');
const progressText = $('progressText');
const resultsSection = $('resultsSection');
const resultCount = $('resultCount');
const mapList = $('mapList');
const statsRow = $('statsRow');
const emptyState = $('emptyState');
// ---- 工具 ----
function updateStatus(type, message) {
statusDot.className = 'dot';
if (type === 'scanning') statusDot.classList.add('yellow');
else if (type === 'success') statusDot.classList.add('green');
else if (type === 'error') statusDot.classList.add('red');
else statusDot.classList.add('gray');
statusText.textContent = message;
}
function updateProgress(current, total, extra) {
progressContainer.style.display = 'block';
const pct = total > 0 ? Math.round((current / total) * 100) : 0;
progressFill.style.width = pct + '%';
progressText.textContent = extra || (current + '/' + total + ' (' + pct + '%)');
}
function showProgress(show) {
progressContainer.style.display = show ? 'block' : 'none';
}
function formatSize(bytes) {
if (bytes < 1024) return bytes + ' B';
if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
}
function escHtml(str) {
return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
}
function disableButtons(val) {
btnScan.disabled = val;
btnDownloadMaps.disabled = val;
btnDownloadAll.disabled = val;
}
// ---- 渲染 ----
function renderResults(result) {
if (!result || !result.maps || result.maps.length === 0) {
resultsSection.style.display = 'none';
emptyState.style.display = 'block';
emptyState.innerHTML = '<div class="icon">✅</div><p>未发现 .map 文件泄露</p><p class="hint">已检查 ' + (result.totalJs || '?') + ' 个 JS 文件</p>';
btnDownloadMaps.disabled = true;
btnDownloadAll.disabled = true;
return;
}
state.scanResult = result;
resultsSection.style.display = 'block';
emptyState.style.display = 'none';
resultCount.textContent = result.maps.length + ' 个';
btnDownloadMaps.disabled = false;
btnDownloadAll.disabled = false;
let html = '';
for (const map of result.maps) {
const jsName = (map.jsUrl || '').split('/').pop().split('?')[0] || '?';
const mapName = (map.mapUrl || '').split('/').pop().split('?')[0] || '?';
html += '<div class="map-item"><span class="file-icon">📄</span><div class="file-info">';
html += '<div class="file-name" title="' + escHtml(map.mapUrl) + '">' + escHtml(mapName) + '</div>';
html += '<div class="file-meta">JS: ' + escHtml(jsName);
if (map.jsSize) html += '<span class="tag info">' + formatSize(map.jsSize) + '</span>';
html += '</div></div></div>';
}
mapList.innerHTML = html;
statsRow.innerHTML =
'<span class="stat-chip">📜 JS: <strong>' + (result.totalJs || '?') + '</strong></span>' +
'<span class="stat-chip">🗺️ .map: <strong>' + result.maps.length + '</strong></span>' +
'<span class="stat-chip">📁 预计源码: <strong>' + (result.maps.length * 30) + '+</strong></span>';
chrome.action.setBadgeText({ text: String(result.maps.length) });
chrome.action.setBadgeBackgroundColor({ color: '#e74c3c' });
}
// ---- 收集 JS URL(content 优先,background 兜底) ----
async function collectJsUrls() {
// 方式1: content script(有 performance.getEntriesByType 历史数据)
try {
const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
if (tabs && tabs[0]) {
const resp = await chrome.tabs.sendMessage(tabs[0].id, { action: 'scan' });
if (resp && resp.success && resp.data && resp.data.jsUrls.length > 0) {
return { jsUrls: resp.data.jsUrls, jsCount: resp.data.jsUrls.length, source: 'content' };
}
}
} catch (e) {
// content script 未注入或页面不能访问
}
// 方式2: background webRequest(兜底)
try {
const resp = await chrome.runtime.sendMessage({ action: 'getTabJsUrls' });
if (resp && resp.success && resp.jsUrls && resp.jsUrls.length > 0) {
return { jsUrls: resp.jsUrls, jsCount: resp.jsUrls.length, source: 'webRequest' };
}
} catch (e) { /* ignore */ }
return { jsUrls: [], jsCount: 0, source: 'none' };
}
// ---- 扫描 ----
async function startScan() {
if (state.isScanning) return;
state.isScanning = true;
btnScan.disabled = true;
btnScan.innerHTML = '<span class="btn-icon">⏳</span> 扫描中...';
updateStatus('scanning', '正在收集页面 JS URL...');
showProgress(false);
resultsSection.style.display = 'none';
emptyState.style.display = 'none';
try {
const { jsUrls, jsCount, source } = await collectJsUrls();
if (jsCount === 0) {
updateStatus('success', '未发现 JS 文件');
emptyState.style.display = 'block';
emptyState.innerHTML = '<div class="icon">⚠️</div><p>未发现 JS 文件</p><p class="hint">请确认页面已加载完毕(含动态脚本),然后重新扫描</p>';
state.isScanning = false;
btnScan.disabled = false;
btnScan.innerHTML = '<span class="btn-icon">🔎</span> 重新扫描';
return;
}
updateStatus('scanning', '发现 ' + jsCount + ' 个 JS 文件(来源: ' + source + '),正在检测 .map...');
updateProgress(0, jsCount, '准备检测...');
showProgress(true);
// 发送给 background 检测 sourceMappingURL
chrome.runtime.sendMessage({ action: 'checkMaps', urls: jsUrls }).catch(() => {});
} catch (err) {
console.error('Scan error:', err);
updateStatus('error', '扫描失败: ' + err.message);
emptyState.style.display = 'block';
emptyState.innerHTML = '<div class="icon">⚠️</div><p>扫描出错</p><p class="hint">' + escHtml(err.message) + '</p>';
state.isScanning = false;
btnScan.disabled = false;
btnScan.innerHTML = '<span class="btn-icon">🔎</span> 重新扫描';
}
}
// ---- 下载 ----
async function downloadMapsOnly() {
if (state.isDownloading || !state.scanResult || !state.scanResult.maps.length) return;
state.isDownloading = true;
disableButtons(true);
updateStatus('scanning', '下载 .map 文件中...');
showProgress(true);
const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
chrome.runtime.sendMessage({
action: 'downloadMapsOnly',
data: { maps: state.scanResult.maps, pageUrl: tabs[0].url },
}).catch(() => {});
}
async function downloadAllSources() {
if (state.isDownloading || !state.scanResult || !state.scanResult.maps.length) return;
state.isDownloading = true;
disableButtons(true);
updateStatus('scanning', '下载并解析 .map 文件...');
showProgress(true);
const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
chrome.runtime.sendMessage({
action: 'downloadAll',
data: { maps: state.scanResult.maps, pageUrl: tabs[0].url },
}).catch(() => {});
}
// ---- 消息监听 ----
chrome.runtime.onMessage.addListener((message) => {
if (message.action === 'mapsFound') {
state.isScanning = false;
btnScan.disabled = false;
btnScan.innerHTML = '<span class="btn-icon">🔎</span> 重新扫描';
showProgress(false);
const data = message.data;
if (data.maps.length > 0) {
updateStatus('success', '发现 ' + data.maps.length + ' 个 .map 文件(共 ' + data.totalJs + ' 个 JS)');
renderResults(data);
} else {
updateStatus('success', '未发现 .map 文件(检查了 ' + data.totalJs + ' 个 JS)');
state.scanResult = null;
resultsSection.style.display = 'none';
emptyState.style.display = 'block';
emptyState.innerHTML = '<div class="icon">✅</div><p>未发现 .map 文件泄露</p><p class="hint">已检查 ' + data.totalJs + ' 个 JS 文件</p>';
}
}
if (message.action === 'progress') {
const d = message.data;
if (d.status === 'packing') {
progressFill.style.background = 'linear-gradient(90deg, #27ae60, #2ecc71)';
updateProgress(100, 100, '正在打包 ' + d.sourceCount + ' 个源码文件...');
} else if (d.total && d.current) {
updateProgress(d.current, d.total, '解析 .map: ' + d.current + '/' + d.total);
}
}
if (message.action === 'downloadComplete') {
state.isDownloading = false;
disableButtons(false);
progressFill.style.width = '100%';
progressFill.style.background = 'linear-gradient(90deg, #27ae60, #2ecc71)';
const d = message.data;
const parts = [];
const stats = d.typeStats || {};
for (const ext in stats) {
if (Object.prototype.hasOwnProperty.call(stats, ext)) parts.push('.' + ext + ':' + stats[ext]);
}
let statusMsg = '✅ 下载完成! ' + (d.sourceCount || d.mapCount || '?') + ' 个文件';
if (d.failedCount > 0) {
statusMsg += ' · ⚠️ ' + d.failedCount + ' 个 .map 解析失败';
progressFill.style.background = 'linear-gradient(90deg, #f39c12, #e74c3c)';
}
updateStatus(d.failedCount > 0 ? 'error' : 'success', statusMsg);
progressText.textContent = parts.length > 0 ? '文件类型: ' + parts.join(', ') : '下载完成';
setTimeout(() => showProgress(false), 5000);
}
if (message.action === 'downloadError') {
state.isDownloading = false;
disableButtons(false);
showProgress(false);
updateStatus('error', '下载失败: ' + ((message.data && message.data.error) || 'unknown'));
}
});
// ---- 初始化 ----
async function init() {
try {
const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
if (tabs && tabs[0]) {
urlPreview.textContent = new URL(tabs[0].url).hostname;
}
} catch (e) { urlPreview.textContent = ''; }
}
btnScan.addEventListener('click', startScan);
btnDownloadMaps.addEventListener('click', downloadMapsOnly);
btnDownloadAll.addEventListener('click', downloadAllSources);
document.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !state.isScanning) startScan();
if (e.key === 's' && e.ctrlKey && !state.isScanning) { e.preventDefault(); startScan(); }
});
init();