-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
726 lines (666 loc) · 39.3 KB
/
Copy pathscript.js
File metadata and controls
726 lines (666 loc) · 39.3 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
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
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
// =============================================================================
// StorageManager script.js v1.1.0
//
// Bug Fix v1.1.0:
// [BUG-1] htmlEscape strips control characters to prevent layout corruption.
// [BUG-3] Debounce (500ms) on inline editing to prevent orphan storage entries.
// [BUG-4] CookieManager.set() preserves domain/path/secure/httpOnly/sameSite.
// [BUG-5] CookieManager.remove()/clear() uses proper URL per cookie.
// [BUG-6] Full cookie objects stored in cookieCache; duplicate names supported.
// [BUG-7] URL.revokeObjectURL() called after export download.
// [BUG-8] Guard for empty currentTabUrl before any storage/cookie operation.
// [BUG-9] Preference stored in chrome.storage.local, not popup localStorage.
// [BUG-10] Focus state (row, column, cursor) saved/restored across renderTable.
// [BUG-11] Readonly cookie key inputs have descriptive tooltips.
// [BUG-12] file: protocol no longer unconditionally blocked.
// [BUG-13] Export/Import buttons visible for Cookies (now fully functional).
// [BUG-14] Import catches QuotaExceededError per-item inside injectedFunction.
// [BUG-15] Toast removal has fallback setTimeout if CSS animation doesn't fire.
// =============================================================================
(function(window, document, chrome) {
'use strict';
// BUG-9: Initialize default; actual preference loaded async from chrome.storage.local
let currentType = 'L';
let currentTabId = null;
let currentTabUrl = '';
let cookieCache = []; // BUG-6: Store full cookie objects from chrome.cookies API
const pendingEdits = new Map(); // BUG-3/26: Per-row debounce timers for inline editing
const els = {
tabs: {
L: document.getElementById('tab-local'),
S: document.getElementById('tab-session'),
C: document.getElementById('tab-cookies'),
A: document.getElementById('tab-about')
},
tabSlider: document.querySelector('.tab-slider'),
buttons: document.getElementById('buttons'),
table: document.getElementById('table'),
importSection: document.getElementById('import-section'),
aboutView: document.getElementById('about-view'),
appName: document.getElementById('app-name'),
appAuthor: document.getElementById('app-author'),
appGithub: document.getElementById('app-github'),
appVersion: document.getElementById('app-version'),
jsonModal: document.getElementById('json'),
jsonCode: document.getElementById('code'),
jsonTitle: document.getElementById('json-title-text'),
importText: document.getElementById('import-text'),
importFile: document.getElementById('import-file'),
importFileLabel: document.getElementById('import-file-label'),
fileNameText: document.getElementById('file-name-text'),
toastContainer: document.getElementById('toast-container'),
confirmModal: document.getElementById('confirm-modal'),
confirmTitle: document.getElementById('confirm-title'),
confirmMsg: document.getElementById('confirm-msg'),
confirmOk: document.getElementById('confirm-ok'),
confirmCancel: document.getElementById('confirm-cancel'),
btn: {
add: document.getElementById('add'),
reload: document.getElementById('reload'),
clear: document.getElementById('clear'),
copy: document.getElementById('copy'),
import: document.getElementById('import'),
download: document.getElementById('download'),
closeJson: document.getElementById('close-json'),
cancelImport: document.getElementById('btn-cancel-import'),
processImport: document.getElementById('btn-process-import')
}
};
const icons = {
trash: `<svg xmlns="http://www.w3.org/2000/svg" class="icon-svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" /></svg>`,
eye: `<svg xmlns="http://www.w3.org/2000/svg" class="icon-svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" /><path stroke-linecap="round" stroke-linejoin="round" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" /></svg>`,
check: `<svg xmlns="http://www.w3.org/2000/svg" class="icon-svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7" /></svg>`,
cross: `<svg xmlns="http://www.w3.org/2000/svg" class="icon-svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" /></svg>`,
empty: `<svg xmlns="http://www.w3.org/2000/svg" class="empty-svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5"><path stroke-linecap="round" stroke-linejoin="round" d="M5 19a2 2 0 01-2-2V7a2 2 0 012-2h4l2 2h4a2 2 0 012 2v1M5 19h14a2 2 0 002-2v-5a2 2 0 00-2-2H9a2 2 0 00-2 2v5a2 2 0 01-2 2z" /></svg>`,
restricted: `<svg xmlns="http://www.w3.org/2000/svg" class="empty-svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5"><path stroke-linecap="round" stroke-linejoin="round" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" /></svg>`
};
function showToast(message, type = 'success') {
const toast = document.createElement('div');
toast.className = `toast ${type}`;
const iconSvg = type === 'success'
? `<svg class="icon-svg" viewBox="0 0 20 20" fill="currentColor"><path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"/></svg>`
: `<svg class="icon-svg" viewBox="0 0 20 20" fill="currentColor"><path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clip-rule="evenodd"/></svg>`;
// BUG-16: Use textContent for message to prevent XSS via error strings
toast.innerHTML = iconSvg;
const msgSpan = document.createElement('span');
msgSpan.textContent = message;
toast.appendChild(msgSpan);
els.toastContainer.appendChild(toast);
setTimeout(() => {
toast.classList.add('fading');
// BUG-15: Fallback removal if CSS animation doesn't fire
const cleanup = () => { if (toast.parentNode) toast.remove(); };
toast.addEventListener('animationend', cleanup);
setTimeout(cleanup, 500);
}, 3000);
}
let confirmCallback = null;
function showConfirm(title, message, callback) {
els.confirmTitle.textContent = title; els.confirmMsg.textContent = message;
confirmCallback = callback; els.confirmModal.style.display = 'flex';
}
function hideConfirm() { els.confirmModal.style.display = 'none'; confirmCallback = null; }
// BUG-24: Capture and null-out callback before execution to prevent stale callback race
els.confirmOk.addEventListener('click', () => { const cb = confirmCallback; hideConfirm(); if (cb) cb(); });
els.confirmCancel.addEventListener('click', hideConfirm);
function injectedFunction(msg) {
function getStorage() {
var obj = {};
var storage = msg.type === 'L' ? window.localStorage : window.sessionStorage;
if (!storage) return;
for (var i in storage) { if (storage.hasOwnProperty(i)) obj[i] = storage.getItem(i); }
return obj;
}
var storage = msg.type === 'L' ? window.localStorage : window.sessionStorage;
if (!storage) return undefined;
switch (msg.what) {
case 'get': return getStorage();
case 'remove': storage.removeItem(msg.key); break;
case 'set':
if (msg.oldKey !== undefined && msg.oldKey !== msg.key) storage.removeItem(msg.oldKey);
storage.setItem(msg.key, msg.value);
break;
case 'clear': storage.clear(); break;
case 'export': return JSON.stringify(getStorage(), null, 4);
case 'import':
try {
// BUG-39: Renamed to avoid shadowing getStorage's var obj
var importData = JSON.parse(msg.json);
// BUG-14: try-catch per item to handle QuotaExceededError gracefully
var errors = [];
for (var i in importData) {
if (importData.hasOwnProperty(i)) {
try {
storage.setItem(i, importData[i]);
} catch(itemErr) {
errors.push(i + ': ' + itemErr.message);
}
}
}
if (errors.length > 0) return {error: 'Partial import. Failed: ' + errors.join('; ')};
} catch(e) { return {error: e.message}; }
break;
}
}
// ==========================================================================
// BUG-4/5/6: Refactored CookieManager with full metadata preservation
// ==========================================================================
const CookieManager = {
_getCookieUrl(cookie) {
// BUG-5: Construct proper URL using the cookie's own domain and path
const protocol = cookie.secure ? 'https:' : 'http:';
const domain = cookie.domain.startsWith('.') ? cookie.domain.substring(1) : cookie.domain;
return `${protocol}//${domain}${cookie.path}`;
},
getAll(callback) {
// BUG-8: Guard for empty URL
if (!currentTabUrl) { callback(null); return; }
chrome.cookies.getAll({ url: currentTabUrl }, (cookies) => {
// BUG-6: Store full cookie objects for later use
cookieCache = cookies || [];
callback(cookieCache);
});
},
set(index, value) {
const cookie = cookieCache[index];
if (!cookie) return;
// BUG-4: Preserve ALL cookie metadata when updating value
const details = {
url: this._getCookieUrl(cookie),
name: cookie.name,
value: value,
storeId: cookie.storeId
};
if (cookie.domain) details.domain = cookie.domain;
if (cookie.path) details.path = cookie.path;
if (cookie.secure !== undefined) details.secure = cookie.secure;
if (cookie.httpOnly !== undefined) details.httpOnly = cookie.httpOnly;
if (cookie.sameSite) details.sameSite = cookie.sameSite;
if (cookie.expirationDate) details.expirationDate = cookie.expirationDate;
chrome.cookies.set(details);
cookie.value = value; // Update cache in-place
},
remove(index, callback) {
const cookie = cookieCache[index];
if (!cookie) { if (callback) callback(); return; }
// BUG-5: Use proper URL with cookie's actual domain and path
chrome.cookies.remove({
url: this._getCookieUrl(cookie),
name: cookie.name,
storeId: cookie.storeId
}, callback);
},
clear(callback) {
if (cookieCache.length === 0) { if (callback) callback(); return; }
// BUG-5/29: Remove each cookie; use allSettled so one failure doesn't block the rest
Promise.allSettled(cookieCache.map(cookie =>
chrome.cookies.remove({
url: this._getCookieUrl(cookie),
name: cookie.name,
storeId: cookie.storeId
})
)).then((results) => {
const failed = results.filter(r => r.status === 'rejected').length;
cookieCache = [];
if (callback) callback(failed > 0 ? { warning: `${failed} cookie(s) failed to delete` } : null);
});
}
};
// BUG-21: Always invoke callback even if no tab found (prevents blank popup)
function getActiveTab(callback) {
chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
if (tabs && tabs[0]) {
currentTabId = tabs[0].id;
currentTabUrl = tabs[0].url || '';
}
callback();
});
}
function executeAction(action, data = {}, callback) {
// BUG-8: Guard for empty/missing tab URL
if (!currentTabUrl) {
if (callback) callback({ error: 'NO_TAB_URL' });
return;
}
// BUG-12: Removed 'file:' — let injection attempt naturally; it works if user
// enabled "Allow access to file URLs" in extension settings.
const isRestricted = currentTabUrl.startsWith('chrome:') || currentTabUrl.startsWith('edge:') ||
currentTabUrl.startsWith('about:') || currentTabUrl.startsWith('brave:');
if (isRestricted) { if (callback) callback({ error: 'RESTRICTED_PAGE' }); return; }
if (currentType === 'C') {
if (action === 'get') {
CookieManager.getAll(callback);
} else if (action === 'set') {
// BUG-4: Index-based set preserves full cookie metadata
if (data.cookieIdx !== undefined) {
CookieManager.set(data.cookieIdx, data.value);
}
if (callback) callback();
} else if (action === 'remove') {
if (data.cookieIdx !== undefined) {
CookieManager.remove(data.cookieIdx, callback);
} else {
if (callback) callback();
}
} else if (action === 'clear') {
CookieManager.clear(callback);
} else if (action === 'export' && callback) {
// BUG-4/6: Export with full cookie metadata
callback(JSON.stringify(cookieCache.map(c => ({
name: c.name, value: c.value, domain: c.domain, path: c.path,
secure: c.secure, httpOnly: c.httpOnly, sameSite: c.sameSite,
expirationDate: c.expirationDate
})), null, 4));
} else if (action === 'import') {
try {
const parsed = JSON.parse(data.json);
if (Array.isArray(parsed)) {
// New format: array of full cookie objects (from our export)
parsed.forEach(c => {
if (!c.name) return;
const details = { url: currentTabUrl, name: c.name, value: c.value || '' };
if (c.domain) details.domain = c.domain;
if (c.path) details.path = c.path;
if (c.secure !== undefined) details.secure = c.secure;
if (c.httpOnly !== undefined) details.httpOnly = c.httpOnly;
if (c.sameSite) details.sameSite = c.sameSite;
if (c.expirationDate) details.expirationDate = c.expirationDate;
chrome.cookies.set(details);
});
} else {
// Legacy format: {name: value} pairs
for (let key in parsed) {
if (parsed.hasOwnProperty(key)) {
chrome.cookies.set({ url: currentTabUrl, name: key, value: String(parsed[key]) });
}
}
}
if (callback) callback();
} catch(e) {
if (callback) callback({ error: e.message });
}
}
} else {
const msg = { type: currentType, what: action, ...data };
chrome.scripting.executeScript({
target: { tabId: currentTabId },
func: injectedFunction,
args: [msg]
}).then((results) => {
const res = results && results[0] ? results[0].result : undefined;
if (callback) callback(res);
}).catch((err) => {
console.warn("StorageManager: Injection failed", err);
if (callback) callback({ error: 'INJECTION_FAILED' });
});
}
}
// Slide the tab indicator to the active tab button
function moveSlider() {
const activeBtn = els.tabs[currentType];
if (!activeBtn || !els.tabSlider) return;
const container = activeBtn.parentElement;
const containerRect = container.getBoundingClientRect();
const btnRect = activeBtn.getBoundingClientRect();
els.tabSlider.style.left = (btnRect.left - containerRect.left) + 'px';
els.tabSlider.style.width = btnRect.width + 'px';
}
function updateUIState() {
Object.keys(els.tabs).forEach(k => els.tabs[k].classList.toggle('active', k === currentType));
moveSlider();
closeAndResetImport(); // BUG-40: Reset import data when switching tabs
if (currentType === 'A') {
els.aboutView.classList.remove('hidden'); els.buttons.style.display = 'none'; els.table.style.display = 'none';
// Retrigger entrance animation by removing and re-adding the class
const container = els.aboutView.querySelector('.about-container');
if (container) {
container.classList.remove('about-animate');
void container.offsetWidth; // Force reflow to reset animations
container.classList.add('about-animate');
}
} else {
els.aboutView.classList.add('hidden'); els.buttons.style.display = 'flex'; els.table.style.display = 'block';
// Remove animate class so it retriggers next time
const container = els.aboutView.querySelector('.about-container');
if (container) container.classList.remove('about-animate');
// BUG-13: Show all buttons including storage-only (cookie export/import now works)
const storageOnlyBtns = document.querySelectorAll('.storage-only');
storageOnlyBtns.forEach(el => el.style.display = 'flex');
}
}
function renderTable() {
if (currentType === 'A') return;
// BUG-10: Save focus state before rebuilding the table
const activeEl = document.activeElement;
let savedFocus = null;
if (activeEl && activeEl.tagName === 'INPUT' && els.table.contains(activeEl)) {
const tr = activeEl.closest('tr');
if (tr && !tr.classList.contains('new-row')) {
const tbody = tr.closest('tbody');
savedFocus = {
rowIndex: tbody ? Array.from(tbody.children).indexOf(tr) : -1,
isValue: activeEl.parentElement.classList.contains('td-value'),
selStart: activeEl.selectionStart,
selEnd: activeEl.selectionEnd
};
}
}
executeAction('get', {}, function(data) {
let html = '';
let storageName = 'Unknown';
if (currentType === 'L') storageName = 'Local Storage';
else if (currentType === 'S') storageName = 'Session Storage';
else if (currentType === 'C') storageName = 'Cookies';
// Check for error responses (always plain objects with .error)
const isRestricted = data && typeof data === 'object' && !Array.isArray(data) &&
(data.error === 'RESTRICTED_PAGE' || data.error === 'INJECTION_FAILED' || data.error === 'NO_TAB_URL');
if (isRestricted) {
els.buttons.style.display = 'none';
html = `<div class="empty-state"><div class="empty-icon-wrapper restricted">${icons.restricted}</div><p>Cannot access data on <br><strong>Browser System Page</strong></p></div>`;
} else if (currentType === 'C') {
// ======================================================
// BUG-6: Cookie rendering from full cookie objects array
// ======================================================
els.buttons.style.display = 'flex';
if (!data || data.length === 0) {
html = `<div class="empty-state"><div class="empty-icon-wrapper">${icons.empty}</div><p>No data found in <br><strong>${storageName}</strong></p></div>`;
} else {
html += `<table><thead><tr><th style="width: 35%">Name</th><th style="width: 50%">Value</th><th style="width: 15%; text-align:center">Action</th></tr></thead><tbody>`;
data.forEach((cookie, idx) => {
const safeName = htmlEscape(cookie.name);
const safeVal = htmlEscape(cookie.value);
const domainPath = htmlEscape(`${cookie.domain}${cookie.path}`);
const flags = [];
if (cookie.secure) flags.push('Secure');
if (cookie.httpOnly) flags.push('HttpOnly');
const flagStr = flags.length > 0 ? ' · ' + flags.join(' · ') : '';
// BUG-11: Tooltip explains readonly + shows domain/path info
html += `<tr data-cookie-idx="${idx}">` +
`<td class="td-nome">` +
`<input type="text" value="${safeName}" data-key="${safeName}" readonly title="Cookie name is read-only. Use Delete + Add to rename.">` +
`<div class="cookie-meta">${domainPath}${flagStr}</div>` +
`</td>` +
`<td class="td-value"><input type="text" value="${safeVal}"></td>` +
`<td style="text-align:center; white-space:nowrap;">` +
`<span class="td-icon open" title="View Detail">${icons.eye}</span>` +
`<span class="td-icon minus" title="Delete">${icons.trash}</span>` +
`</td></tr>`;
});
html += `</tbody></table>`;
}
} else {
// ======================================================
// LocalStorage / SessionStorage (original logic)
// ======================================================
els.buttons.style.display = 'flex';
if (!data || Object.keys(data).length === 0) {
html = `<div class="empty-state"><div class="empty-icon-wrapper">${icons.empty}</div><p>No data found in <br><strong>${storageName}</strong></p></div>`;
} else {
html += `<table><thead><tr><th style="width: 35%">Key / Name</th><th style="width: 50%">Value</th><th style="width: 15%; text-align:center">Action</th></tr></thead><tbody>`;
for (let key in data) {
const safeKey = htmlEscape(key); const safeVal = htmlEscape(data[key]);
html += `<tr><td class="td-nome"><input type="text" value="${safeKey}" data-key="${safeKey}"></td>` +
`<td class="td-value"><input type="text" value="${safeVal}"></td>` +
`<td style="text-align:center; white-space:nowrap;">` +
`<span class="td-icon open" title="View Detail">${icons.eye}</span>` +
`<span class="td-icon minus" title="Delete">${icons.trash}</span>` +
`</td></tr>`;
}
html += `</tbody></table>`;
}
}
els.table.innerHTML = html;
// BUG-10: Restore focus after rebuild
if (savedFocus && savedFocus.rowIndex >= 0) {
const tbody = els.table.querySelector('tbody');
if (tbody && savedFocus.rowIndex < tbody.children.length) {
const tr = tbody.children[savedFocus.rowIndex];
const input = savedFocus.isValue
? tr.querySelector('.td-value input')
: tr.querySelector('.td-nome input');
if (input && !input.readOnly) {
input.focus();
try { input.setSelectionRange(savedFocus.selStart, savedFocus.selEnd); } catch(e) {}
}
}
}
});
}
function showAddRow() {
if (document.querySelector('.new-row')) { document.querySelector('#new-key').focus(); return; }
if (document.querySelector('.empty-state')) { els.table.innerHTML = `<table><thead><tr><th style="width: 35%">Key</th><th style="width: 50%">Value</th><th style="width: 15%; text-align:center">Action</th></tr></thead><tbody></tbody></table>`; }
const tbody = els.table.querySelector('tbody'); if(!tbody) return;
const tr = document.createElement('tr'); tr.className = 'new-row';
tr.innerHTML = `<td class="td-nome"><input type="text" id="new-key" placeholder="New Key Name" autocomplete="off"></td><td class="td-value"><input type="text" id="new-val" placeholder="Value" autocomplete="off"></td><td style="text-align:center; white-space:nowrap;"><span class="td-icon save-new" title="Save">${icons.check}</span><span class="td-icon cancel-new" title="Cancel">${icons.cross}</span></td>`;
tbody.insertBefore(tr, tbody.firstChild);
const newKeyInput = document.getElementById('new-key'); const newValInput = document.getElementById('new-val');
newKeyInput.focus(); newKeyInput.addEventListener('input', function() { this.style.borderColor = ''; });
const handleEnter = (e) => { if (e.key === 'Enter') saveNewRow(); if (e.key === 'Escape') renderTable(); };
newKeyInput.addEventListener('keyup', handleEnter); newValInput.addEventListener('keyup', handleEnter);
}
function saveNewRow() {
const keyInput = document.getElementById('new-key'); const valInput = document.getElementById('new-val');
if (!keyInput || !valInput) return;
const key = keyInput.value.trim(); const val = valInput.value;
if (!key) { showToast('Key name cannot be empty!', 'error'); keyInput.style.borderColor = 'var(--danger)'; keyInput.focus(); return; }
if (currentType === 'C') {
// BUG-31: Guard for empty URL (saveNewRow bypasses executeAction)
if (!currentTabUrl) { showToast('Cannot add cookie: no active page', 'error'); return; }
chrome.cookies.set({ url: currentTabUrl, name: key, value: val }, () => {
renderTable(); showToast('Cookie added successfully');
});
} else {
executeAction('set', {key: key, value: val}, () => { renderTable(); showToast('Item added successfully'); });
}
}
// BUG-1: Enhanced htmlEscape — strips control characters to prevent layout corruption
function htmlEscape(str) {
return String(str)
.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, '') // Strip control chars (keep \t \n \r)
.replace(/[&<>"']/g, m => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[m]));
}
function syntaxHighlight(json) {
return json.replace(/(\"(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*\"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
let cls = 'number'; if (/^"/.test(match)) { if (/:$/.test(match)) cls = 'key'; else cls = 'string'; } else if (/true|false/.test(match)) cls = 'boolean'; else if (/null/.test(match)) cls = 'null';
return '<span class="' + cls + '">' + htmlEscape(match) + '</span>';
});
}
function parseDeepJSON(str) { try { const o = JSON.parse(str); if (o && typeof o === 'object') return o; } catch(e) {} return str; }
function toggleImportSection() {
const isHidden = els.importSection.classList.contains('hidden');
if (isHidden) { els.importSection.classList.remove('hidden'); els.importText.focus(); } else { els.importSection.classList.add('hidden'); }
}
function closeAndResetImport() {
els.importSection.classList.add('hidden');
els.importText.value = ''; els.importFile.value = ''; els.fileNameText.textContent = 'Choose File'; els.importFileLabel.style = '';
}
els.importFile.addEventListener('change', function() {
if (this.files && this.files.length > 0) {
els.fileNameText.textContent = this.files[0].name;
els.importFileLabel.style.borderColor = 'var(--primary)'; els.importFileLabel.style.color = 'var(--primary)';
} else {
els.fileNameText.textContent = "Choose File"; els.importFileLabel.style = '';
}
});
function handleProcessImport() {
const file = els.importFile.files[0]; const text = els.importText.value.trim();
// BUG-37: Removed redundant JSON.parse — executeAction already handles parse errors
const processJSON = (jsonString) => {
executeAction('import', {json: jsonString}, (res) => {
if(res && res.error) { showToast('Import Failed: ' + res.error, 'error'); }
else { closeAndResetImport(); renderTable(); showToast('Data imported successfully'); }
});
};
// BUG-38: Added onerror handler for FileReader
if (file) { const reader = new FileReader(); reader.onload = (e) => processJSON(e.target.result); reader.onerror = () => showToast('Failed to read file', 'error'); reader.readAsText(file); }
else if (text) { processJSON(text); } else { showToast('Please paste JSON text or select a file', 'error'); }
}
// Tab switching
['L', 'S', 'C', 'A'].forEach(t => {
els.tabs[t].addEventListener('click', () => {
currentType = t;
// BUG-9: Use chrome.storage.local instead of localStorage
chrome.storage.local.set({ preferredType: t });
// BUG-41: Clear stale edit timers from previous tab
pendingEdits.forEach(timer => clearTimeout(timer));
pendingEdits.clear();
updateUIState();
renderTable();
});
});
els.btn.reload.addEventListener('click', () => { renderTable(); showToast('Data reloaded'); });
els.btn.add.addEventListener('click', showAddRow);
els.btn.clear.addEventListener('click', () => { showConfirm('Clear All Data?', `This will delete ALL items in ${currentType === 'L' ? 'Local Storage' : (currentType === 'S' ? 'Session Storage' : 'Cookies')}.`, () => { executeAction('clear', {}, () => { renderTable(); showToast('All data cleared'); }); }); });
// BUG-22/32: Check empty + handle clipboard promise rejection
els.btn.copy.addEventListener('click', () => { executeAction('export', {}, (res) => { if(res && res !== '[]' && res !== '{}') { navigator.clipboard.writeText(res).then(() => showToast('Copied to clipboard')).catch(() => showToast('Failed to copy', 'error')); } else { showToast('Nothing to copy', 'error'); } }); });
els.btn.download.addEventListener('click', () => {
let host = 'data'; try { host = new URL(currentTabUrl).hostname; } catch(e){}
const dateStr = new Date().toISOString().slice(0,19).replace(/:/g,'-');
const filename = `${host}-${currentType}-${dateStr}.json`;
executeAction('export', {}, (res) => {
// BUG-33: Also check for empty arrays/objects
if(!res || res === '[]' || res === '{}') { showToast('No data to export', 'error'); return; }
const blob = new Blob([res], {type: 'application/json'}); const url = URL.createObjectURL(blob);
const a = document.createElement('a'); a.href = url; a.download = filename; document.body.appendChild(a); a.click();
// BUG-7: Revoke object URL to prevent memory leak
setTimeout(() => { document.body.removeChild(a); URL.revokeObjectURL(url); }, 100);
showToast('Export successful');
});
});
els.btn.import.addEventListener('click', toggleImportSection);
els.btn.cancelImport.addEventListener('click', closeAndResetImport);
els.btn.processImport.addEventListener('click', handleProcessImport);
// ==========================================================================
// BUG-3/26: Per-row debounced inline editing (500ms)
// Each row gets its own timer so multi-row edits don't cancel each other.
// ==========================================================================
els.table.addEventListener('input', (e) => {
if(e.target.tagName !== 'INPUT' || e.target.closest('.new-row')) return;
const input = e.target; const tr = input.closest('tr');
if (!tr) return;
// BUG-26: Per-row debounce key
const rowKey = (currentType === 'C')
? ('c_' + tr.dataset.cookieIdx)
: ('s_' + (tr.querySelector('.td-nome input')?.dataset.key || ''));
if (pendingEdits.has(rowKey)) clearTimeout(pendingEdits.get(rowKey));
pendingEdits.set(rowKey, setTimeout(() => {
pendingEdits.delete(rowKey);
// BUG-30: Guard against row removed from DOM during debounce wait
if (!input.parentElement || !tr.parentElement) return;
const isValue = input.parentElement.classList.contains('td-value');
if (currentType === 'C') {
// Cookies: only value editing is allowed (key is readonly)
if (!isValue) return;
const cookieIdx = parseInt(tr.dataset.cookieIdx);
if (!isNaN(cookieIdx)) {
CookieManager.set(cookieIdx, input.value);
}
} else {
// LocalStorage / SessionStorage
const keyInput = tr.querySelector('.td-nome input');
const oldKey = keyInput.dataset.key;
const key = keyInput.value;
const value = tr.querySelector('.td-value input').value;
keyInput.dataset.key = key; // Always sync to prevent stale oldKey
executeAction('set', {oldKey, key, value});
}
}, 500));
});
// ==========================================================================
// Table click handler — delete, view, save-new, cancel-new
// ==========================================================================
els.table.addEventListener('click', (e) => {
const icon = e.target.closest('.td-icon'); if(!icon) return; const tr = icon.closest('tr');
if (icon.classList.contains('minus')) {
if (currentType === 'C') {
// BUG-4/5: Cookie deletion uses proper URL from cache
const cookieIdx = parseInt(tr.dataset.cookieIdx);
const cookie = cookieCache[cookieIdx];
const name = cookie ? cookie.name : 'Unknown';
showConfirm('Delete Cookie?', `Are you sure you want to delete "${name}"?`, () => {
CookieManager.remove(cookieIdx, () => {
renderTable();
showToast('Cookie deleted');
});
});
} else {
const key = tr.querySelector('.td-nome input').value;
showConfirm('Delete Item?', `Are you sure you want to delete "${key}"?`, () => {
executeAction('remove', {key}, () => {
tr.remove();
if(!els.table.querySelector('tbody tr')) renderTable();
showToast('Item deleted');
});
});
}
} else if (icon.classList.contains('open')) {
if (currentType === 'C') {
// BUG-6: Show full cookie details including metadata
const cookieIdx = parseInt(tr.dataset.cookieIdx);
const cookie = cookieCache[cookieIdx];
if (!cookie) return;
els.jsonTitle.textContent = "Cookie: " + cookie.name;
const fullObj = {
name: cookie.name,
value: cookie.value,
domain: cookie.domain,
path: cookie.path,
secure: cookie.secure,
httpOnly: cookie.httpOnly,
sameSite: cookie.sameSite || 'unspecified',
session: !cookie.expirationDate,
expires: cookie.expirationDate
? new Date(cookie.expirationDate * 1000).toLocaleString()
: 'Session cookie (no expiration)'
};
els.jsonCode.innerHTML = syntaxHighlight(JSON.stringify(fullObj, null, 4));
} else {
const key = tr.querySelector('.td-nome input').value; let val = tr.querySelector('.td-value input').value;
els.jsonTitle.textContent = "Value: " + key;
let json = parseDeepJSON(val); let displayVal = (typeof json === 'object') ? syntaxHighlight(JSON.stringify(json, null, 4)) : htmlEscape(val);
els.jsonCode.innerHTML = displayVal;
}
els.jsonModal.style.display = 'flex';
} else if (icon.classList.contains('save-new')) {
saveNewRow();
} else if (icon.classList.contains('cancel-new')) {
renderTable();
}
});
els.btn.closeJson.addEventListener('click', () => { els.jsonModal.style.display = 'none'; });
// BUG-19/20/36: Global Escape key handler — only fires when a modal is actually open
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
const confirmOpen = els.confirmModal.style.display === 'flex';
const jsonOpen = els.jsonModal.style.display === 'flex';
if (!confirmOpen && !jsonOpen) return;
if (confirmOpen) hideConfirm();
if (jsonOpen) els.jsonModal.style.display = 'none';
}
});
// Manifest info (runs synchronously)
const manifest = chrome.runtime.getManifest();
els.appName.textContent = manifest.name;
els.appVersion.textContent = manifest.version;
els.appAuthor.textContent = manifest.author || "Unknown Author";
els.appGithub.href = manifest.homepage_url || "#";
// ==========================================================================
// BUG-9: Load preferred tab from chrome.storage.local, then initialize
// ==========================================================================
chrome.storage.local.get('preferredType', (res) => {
const saved = res.preferredType;
if (saved && ['L','S','C','A'].includes(saved)) {
currentType = saved;
}
getActiveTab(() => {
updateUIState();
renderTable();
// Set initial slider position without animation
els.tabSlider.style.transition = 'none';
moveSlider();
requestAnimationFrame(() => {
els.tabSlider.style.transition = '';
});
});
});
})(window, document, chrome);