-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpopup.js
490 lines (419 loc) · 16.8 KB
/
popup.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
let screenshotData = null;
// Add error handling
window.onerror = function(msg, url, lineNo, columnNo, error) {
const statusElement = document.getElementById('status');
if (statusElement) {
statusElement.textContent = 'Error: ' + msg;
}
console.error('Error:', msg, 'at', url, 'line:', lineNo);
return false;
};
document.addEventListener('DOMContentLoaded', function() {
console.log('DOM Content Loaded');
const capturePageBtn = document.getElementById('capturePageBtn');
const captureConsoleBtn = document.getElementById('captureConsoleBtn');
const sendBtn = document.getElementById('sendBtn');
const statusElement = document.getElementById('status');
if (!capturePageBtn || !captureConsoleBtn || !sendBtn) {
console.error('Buttons not found!');
statusElement.textContent = 'Error: UI elements not found';
return;
}
capturePageBtn.addEventListener('click', () => captureScreenshot('page'));
captureConsoleBtn.addEventListener('click', () => captureScreenshot('console'));
sendBtn.addEventListener('click', sendToAPI);
statusElement.textContent = 'Ready to capture';
// Tab switching
const tabs = document.querySelectorAll('.tab-btn');
tabs.forEach(tab => {
tab.addEventListener('click', () => {
// Remove active class from all tabs and contents
document.querySelectorAll('.tab-btn').forEach(t => t.classList.remove('active'));
document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
// Add active class to clicked tab and corresponding content
tab.classList.add('active');
document.getElementById(tab.dataset.tab).classList.add('active');
});
});
// Load saved settings
loadSettings();
// Settings form submission
document.getElementById('settingsForm').addEventListener('submit', async (e) => {
e.preventDefault();
await saveSettings();
});
// Add image preview functionality
const preview = document.getElementById('preview');
const imagePopup = document.getElementById('imagePopup');
const popupImage = document.getElementById('popupImage');
const closePopup = document.querySelector('.close-popup');
// Open popup when clicking the preview image
preview.addEventListener('click', () => {
imagePopup.style.display = 'block';
popupImage.src = preview.src;
});
// Close popup when clicking the close button
closePopup.addEventListener('click', () => {
imagePopup.style.display = 'none';
});
// Close popup when clicking outside the image
imagePopup.addEventListener('click', (e) => {
if (e.target === imagePopup) {
imagePopup.style.display = 'none';
}
});
// Close popup when pressing Escape key
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && imagePopup.style.display === 'block') {
imagePopup.style.display = 'none';
}
});
// Drawing functionality
const canvas = document.getElementById('drawingCanvas');
const ctx = canvas.getContext('2d');
const colorPicker = document.getElementById('colorPicker');
const undoBtn = document.getElementById('undoBtn');
const clearBtn = document.getElementById('clearBtn');
let isDrawing = false;
let lastX = 0;
let lastY = 0;
let drawingHistory = [];
let currentLine = [];
function initCanvas(imgSrc) {
const img = new Image();
img.onload = function() {
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
// Clear history when loading new image
drawingHistory = [];
};
img.src = imgSrc;
}
// Drawing event handlers
canvas.addEventListener('mousedown', startDrawing);
canvas.addEventListener('mousemove', draw);
canvas.addEventListener('mouseup', stopDrawing);
canvas.addEventListener('mouseout', stopDrawing);
function startDrawing(e) {
isDrawing = true;
[lastX, lastY] = [e.offsetX, e.offsetY];
currentLine = []; // Start new line
}
function draw(e) {
if (!isDrawing) return;
const currentPoint = {
x: e.offsetX,
y: e.offsetY,
color: colorPicker.value
};
ctx.beginPath();
ctx.moveTo(lastX, lastY);
ctx.lineTo(currentPoint.x, currentPoint.y);
ctx.strokeStyle = colorPicker.value;
ctx.lineWidth = 2;
ctx.lineCap = 'round';
ctx.stroke();
currentLine.push({
startX: lastX,
startY: lastY,
endX: currentPoint.x,
endY: currentPoint.y,
color: colorPicker.value
});
[lastX, lastY] = [currentPoint.x, currentPoint.y];
}
function stopDrawing() {
if (isDrawing && currentLine.length > 0) {
drawingHistory.push(currentLine);
currentLine = [];
}
isDrawing = false;
}
function redrawCanvas() {
// Clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Redraw original image
const img = new Image();
img.onload = function() {
ctx.drawImage(img, 0, 0);
// Redraw all lines
drawingHistory.forEach(line => {
line.forEach(point => {
ctx.beginPath();
ctx.moveTo(point.startX, point.startY);
ctx.lineTo(point.endX, point.endY);
ctx.strokeStyle = point.color;
ctx.lineWidth = 2;
ctx.lineCap = 'round';
ctx.stroke();
});
});
};
img.src = preview.src;
}
// Tool buttons
undoBtn.addEventListener('click', () => {
if (drawingHistory.length > 0) {
drawingHistory.pop(); // Remove last line
redrawCanvas();
}
});
clearBtn.addEventListener('click', () => {
drawingHistory = []; // Clear history
redrawCanvas();
});
// Modify the existing preview click handler
preview.addEventListener('click', () => {
imagePopup.style.display = 'block';
initCanvas(preview.src);
});
// Save changes when closing popup
closePopup.addEventListener('click', () => {
screenshotData = canvas.toDataURL('image/png');
preview.src = screenshotData;
imagePopup.style.display = 'none';
});
// Add this near the top of your existing DOMContentLoaded listener
const extensionToggle = document.getElementById('extensionToggle');
const container = document.querySelector('.container');
// Load saved state
chrome.storage.sync.get(['extensionEnabled'], function(result) {
const enabled = result.extensionEnabled !== false; // Default to enabled
extensionToggle.checked = enabled;
updateExtensionState(enabled);
});
// Handle toggle
extensionToggle.addEventListener('change', function() {
const enabled = this.checked;
chrome.storage.sync.set({ extensionEnabled: enabled });
updateExtensionState(enabled);
});
function updateExtensionState(enabled) {
if (enabled) {
container.classList.remove('disabled');
} else {
container.classList.add('disabled');
}
}
});
async function captureScreenshot(type) {
const statusElement = document.getElementById('status');
console.log(`Attempting to capture ${type} screenshot...`);
try {
// Get the current active tab
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
if (type === 'console') {
// Inject the content script first
await chrome.scripting.executeScript({
target: { tabId: tab.id },
files: ['content.js']
});
// Get stored console messages
const messages = await new Promise((resolve) => {
chrome.tabs.sendMessage(tab.id, { action: 'getConsoleMessages' }, (response) => {
if (chrome.runtime.lastError) {
console.error('Error getting messages:', chrome.runtime.lastError);
resolve([]);
return;
}
resolve(response?.messages || []);
});
});
// Create overlay with messages
await chrome.scripting.executeScript({
target: { tabId: tab.id },
function: (messages) => {
const overlay = document.createElement('div');
overlay.id = 'console-overlay';
overlay.style.cssText = `
position: fixed;
top: 0;
right: 0;
width: 50%;
height: 100%;
background: #242424;
color: #fff;
font-family: monospace;
padding: 20px;
box-sizing: border-box;
z-index: 999999;
overflow: auto;
`;
// Add header
const header = document.createElement('div');
header.style.cssText = `
font-size: 14px;
font-weight: bold;
margin-bottom: 10px;
padding-bottom: 5px;
border-bottom: 1px solid #444;
`;
header.textContent = 'Console Output';
overlay.appendChild(header);
if (messages.length > 0) {
messages.forEach(msg => {
const line = document.createElement('div');
line.style.cssText = `
margin: 5px 0;
padding: 5px;
border-bottom: 1px solid #333;
white-space: pre-wrap;
font-size: 12px;
`;
let prefix = '';
switch(msg.type) {
case 'error': prefix = '❌'; break;
case 'warn': prefix = '⚠️'; break;
case 'info': prefix = 'ℹ️'; break;
default: prefix = '📋';
}
line.textContent = `${prefix} ${msg.type}: ${msg.text}`;
overlay.appendChild(line);
});
} else {
const line = document.createElement('div');
line.style.cssText = `
margin: 5px 0;
padding: 5px;
border-bottom: 1px solid #333;
white-space: pre-wrap;
font-size: 12px;
color: #888;
`;
line.textContent = 'No console messages found';
overlay.appendChild(line);
}
document.body.appendChild(overlay);
},
args: [messages]
});
// Wait for overlay to render
await new Promise(resolve => setTimeout(resolve, 500));
}
// Capture the visible area of the tab
const screenshot = await chrome.tabs.captureVisibleTab(null, {
format: 'png',
quality: 100
});
if (type === 'console') {
// Clean up overlay and detach debugger
await chrome.scripting.executeScript({
target: { tabId: tab.id },
function: () => {
const overlay = document.getElementById('console-overlay');
if (overlay) overlay.remove();
}
});
try {
await chrome.debugger.detach({ tabId: tab.id });
} catch (e) {
console.error('Error detaching debugger:', e);
}
}
// Show the screenshot preview
const preview = document.getElementById('preview');
preview.src = screenshot;
screenshotData = screenshot;
// Show the screenshot container
const container = document.getElementById('screenshotContainer');
container.style.display = 'block';
statusElement.textContent = 'Screenshot captured!';
} catch (err) {
console.error('Failed to capture screenshot:', err);
statusElement.textContent = 'Error: ' + err.message;
// Clean up if there was an error
try {
await chrome.debugger.detach({ tabId: tab.id });
} catch (e) {
console.error('Error detaching debugger:', e);
}
}
}
async function loadSettings() {
const settings = await chrome.storage.sync.get(['apiUrl', 'apiToken', 'username']);
if (settings.apiUrl) document.getElementById('apiUrl').value = settings.apiUrl;
if (settings.apiToken) document.getElementById('apiToken').value = settings.apiToken;
if (settings.username) document.getElementById('username').value = settings.username;
}
async function saveSettings() {
const settings = {
apiUrl: document.getElementById('apiUrl').value,
apiToken: document.getElementById('apiToken').value,
username: document.getElementById('username').value
};
await chrome.storage.sync.set(settings);
document.getElementById('status').textContent = 'Settings saved!';
setTimeout(() => {
document.getElementById('status').textContent = '';
}, 2000);
}
async function sendToAPI() {
const notes = document.getElementById('notes').value;
const statusElement = document.getElementById('status');
const loaderOverlay = document.querySelector('.loader-overlay');
if (!screenshotData) {
statusElement.textContent = 'No screenshot taken';
return;
}
// Get settings
const settings = await chrome.storage.sync.get(['apiUrl', 'apiToken', 'username']);
if (!settings.apiUrl || !settings.apiToken || !settings.username) {
statusElement.textContent = 'Please configure settings first';
return;
}
// Show loader
loaderOverlay.style.display = 'flex';
statusElement.textContent = 'Sending to API...';
try {
// Get current tab URL
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
const currentUrl = tab.url;
// Get IP address
let ipAddress;
try {
const response = await fetch('https://api.ipify.org?format=json');
const data = await response.json();
ipAddress = data.ip;
} catch (error) {
console.error('Failed to get IP:', error);
ipAddress = 'unknown';
}
// Get user agent
const userAgent = navigator.userAgent;
const response = await fetch(settings.apiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${settings.apiToken}`
},
body: JSON.stringify({
image: screenshotData,
notes: notes,
username: settings.username,
ip: ipAddress,
userAgent: userAgent,
timestamp: new Date().toISOString(),
url: currentUrl
})
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.msg || 'Network response was not ok');
}
// Display the API response message
statusElement.textContent = data.msg || 'Successfully sent to API!';
// Clear the form
document.getElementById('notes').value = '';
document.getElementById('preview').src = '';
document.getElementById('screenshotContainer').style.display = 'none';
screenshotData = null;
} catch (error) {
console.error('Error sending to API:', error);
statusElement.textContent = error.message || 'Failed to send to API';
} finally {
// Hide loader
loaderOverlay.style.display = 'none';
}
}
//# sourceMappingURL=popup.js.map