-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
604 lines (512 loc) · 20.9 KB
/
content.js
File metadata and controls
604 lines (512 loc) · 20.9 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
// Style Injector Content Script (Visual Mode)
let isPicking = false;
let highlightedEl = null;
let overlayEl = null;
let editorEl = null;
let currentSelectedEl = null;
// 初始化:加载规则
init();
// 监听消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.action === 'togglePicker') {
startPicking();
sendResponse({ success: true });
} else if (message.action === 'clearRules') {
clearAllRules();
sendResponse({ success: true });
} else if (message.action === 'editRule') {
const el = document.querySelector(message.selector);
if (el) {
// 滚动到元素位置
el.scrollIntoView({ behavior: 'smooth', block: 'center' });
// 高亮并编辑
selectElement(el);
sendResponse({ success: true });
} else {
showToast('未在页面上找到该元素');
sendResponse({ success: false, error: 'Element not found' });
}
}
});
function init() {
loadAndApplyRules();
}
// ------ 选取逻辑 ------
function startPicking() {
if (isPicking) return;
isPicking = true;
document.body.style.cursor = 'crosshair';
// 创建高亮框
createOverlay();
// 绑定事件
document.addEventListener('mouseover', handleMouseOver, true);
document.addEventListener('click', handleClick, true);
document.addEventListener('keydown', handleKey, true);
showToast('请点击页面上的元素进行修改 (按ESC退出)');
}
function stopPicking() {
isPicking = false;
document.body.style.cursor = '';
if (overlayEl) {
overlayEl.remove();
overlayEl = null;
}
document.removeEventListener('mouseover', handleMouseOver, true);
document.removeEventListener('click', handleClick, true);
document.removeEventListener('keydown', handleKey, true);
}
function handleMouseOver(e) {
if (!isPicking) return;
const target = e.target;
// 忽略插件自己的UI
if (target.closest('#style-injector-editor') || target.closest('#style-injector-overlay')) return;
highlightElement(target);
}
function handleClick(e) {
if (!isPicking) return;
const target = e.target;
// 忽略插件自己的UI
if (target.closest('#style-injector-editor')) return;
e.preventDefault();
e.stopPropagation();
selectElement(target);
stopPicking();
}
function handleKey(e) {
if (e.key === 'Escape') {
if (isPicking) stopPicking();
if (editorEl) closeEditor();
}
}
function highlightElement(el) {
if (!overlayEl) createOverlay();
const rect = el.getBoundingClientRect();
overlayEl.style.top = rect.top + window.scrollY + 'px';
overlayEl.style.left = rect.left + window.scrollX + 'px';
overlayEl.style.width = rect.width + 'px';
overlayEl.style.height = rect.height + 'px';
overlayEl.style.display = 'block';
}
function createOverlay() {
overlayEl = document.createElement('div');
overlayEl.id = 'style-injector-overlay';
overlayEl.style.cssText = `
position: absolute;
border: 2px solid #228be6;
background: rgba(34, 139, 230, 0.1);
z-index: 2147483646;
pointer-events: none;
display: none;
transition: all 0.1s;
`;
document.body.appendChild(overlayEl);
}
// ------ 编辑器逻辑 ------
function selectElement(el) {
currentSelectedEl = el;
try {
showEditor(el);
} catch (e) {
console.error('Style Injector Error:', e);
showToast('无法编辑此元素: ' + e.message);
}
}
function showEditor(targetEl) {
if (editorEl) editorEl.remove();
const selector = getUniqueSelector(targetEl);
editorEl = document.createElement('div');
editorEl.id = 'style-injector-editor';
editorEl.style.cssText = `
position: fixed;
top: 20px;
right: 20px;
width: 300px;
background: white;
border-radius: 8px;
box-shadow: 0 4px 20px rgba(0,0,0,0.2);
z-index: 2147483647;
font-family: sans-serif;
font-size: 13px;
color: #333;
overflow: hidden;
max-height: 90vh;
overflow-y: auto;
`;
editorEl.innerHTML = `
<style>
.si-row { margin-bottom: 16px; }
.si-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px; }
.si-label { font-size: 12px; color: #495057; font-weight: 500; }
.si-input-group { display: flex; align-items: center; }
.si-num-input { width: 50px; padding: 4px; text-align: center; border: 1px solid #dee2e6; border-radius: 4px; font-size: 12px; margin-right: 4px; color: #333; outline: none; }
.si-num-input:focus { border-color: #228be6; }
/* 隐藏数字输入框的上下箭头 */
.si-num-input::-webkit-outer-spin-button,
.si-num-input::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; }
.si-num-input { -moz-appearance: textfield; }
.si-unit { font-size: 11px; color: #868e96; }
.si-slider { width: 100%; margin-top: 4px; accent-color: #228be6; cursor: pointer; }
.si-col-2 { display: flex; gap: 12px; }
.si-col-item { flex: 1; }
.si-color-input { width: 100%; height: 32px; border: 1px solid #dee2e6; border-radius: 4px; padding: 2px; cursor: pointer; box-sizing: border-box; }
/* 美化滚动条 */
#style-injector-editor::-webkit-scrollbar { width: 6px; }
#style-injector-editor::-webkit-scrollbar-thumb { background: #adb5bd; border-radius: 3px; }
</style>
<div style="padding: 14px; background: #f8f9fa; border-bottom: 1px solid #e9ecef; display: flex; justify-content: space-between; align-items: center; position: sticky; top: 0; z-index: 10;">
<span style="font-weight: 700; font-size: 14px; color: #212529;">编辑样式</span>
<button id="si-close-btn" style="border: none; background: none; cursor: pointer; font-size: 20px; color: #868e96; line-height: 1;">×</button>
</div>
<div style="padding: 16px;">
<div class="si-row">
<label class="si-label" style="display:block; margin-bottom:6px;">目标选择器</label>
<input id="si-selector-input" type="text" value="${selector}" style="width: 100%; padding: 6px 8px; background: #fff; border: 1px solid #dee2e6; border-radius: 4px; font-size: 12px; color: #333; box-sizing: border-box; font-family: monospace; outline: none;">
</div>
<div class="si-row" style="padding-bottom: 12px; border-bottom: 1px solid #f1f3f5;">
<label style="display: flex; align-items: center; cursor: pointer;">
<input type="checkbox" id="si-hidden-check" style="margin-right: 8px; accent-color: #fa5252;">
<span class="si-label" style="color: #fa5252;">隐藏此元素</span>
</label>
</div>
<div class="si-row si-col-2">
<div class="si-col-item">
<label class="si-label" style="display:block; margin-bottom:4px;">文字颜色</label>
<input type="color" id="si-color-picker" class="si-color-input">
</div>
<div class="si-col-item">
<label class="si-label" style="display:block; margin-bottom:4px;">背景颜色</label>
<input type="color" id="si-bg-picker" class="si-color-input">
</div>
</div>
<!-- 字体大小 -->
<div class="si-row">
<div class="si-header">
<label class="si-label">字体大小</label>
<div class="si-input-group">
<input type="number" id="si-font-size-input" class="si-num-input">
<span class="si-unit">px</span>
</div>
</div>
<input type="range" id="si-font-size" class="si-slider" min="10" max="100" value="16">
</div>
<!-- 内边距 -->
<div class="si-row">
<div class="si-header">
<label class="si-label">内边距</label>
<div class="si-input-group">
<input type="number" id="si-padding-input" class="si-num-input">
<span class="si-unit">px</span>
</div>
</div>
<input type="range" id="si-padding" class="si-slider" min="0" max="100" value="0">
</div>
<!-- 宽高组合 -->
<div class="si-row si-col-2">
<div class="si-col-item">
<div class="si-header">
<label class="si-label">宽度</label>
<div class="si-input-group">
<input type="number" id="si-width-input" class="si-num-input">
<span class="si-unit">%</span>
</div>
</div>
<input type="range" id="si-width" class="si-slider" min="0" max="100" value="0">
</div>
<div class="si-col-item">
<div class="si-header">
<label class="si-label">高度</label>
<div class="si-input-group">
<input type="number" id="si-height-input" class="si-num-input">
<span class="si-unit">px</span>
</div>
</div>
<input type="range" id="si-height" class="si-slider" min="0" max="100" value="0">
</div>
</div>
<!-- 圆角 -->
<div class="si-row">
<div class="si-header">
<label class="si-label">圆角半径</label>
<div class="si-input-group">
<input type="number" id="si-radius-input" class="si-num-input">
<span class="si-unit">px</span>
</div>
</div>
<input type="range" id="si-radius" class="si-slider" min="0" max="50" value="0">
</div>
<div class="si-row">
<label class="si-label" style="display:block; margin-bottom:6px;">自定义 CSS</label>
<textarea id="si-custom-css" placeholder="border: 1px solid red;" style="width: 100%; height: 60px; padding: 8px; border: 1px solid #dee2e6; border-radius: 4px; font-family: monospace; font-size: 12px; box-sizing: border-box; resize: vertical; background: #f8f9fa;"></textarea>
</div>
<div style="display: flex; gap: 12px; margin-top: 20px;">
<button id="si-cancel-btn" style="flex: 1; padding: 10px; background: #fff; color: #495057; border: 1px solid #dee2e6; border-radius: 6px; cursor: pointer; font-size: 13px; transition: all 0.2s;">取消</button>
<button id="si-save-btn" style="flex: 2; padding: 10px; background: #228be6; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600; font-size: 13px; box-shadow: 0 2px 4px rgba(34, 139, 230, 0.2); transition: all 0.2s;">保存修改</button>
</div>
</div>
`;
document.body.appendChild(editorEl);
// 获取元素引用
const closeBtn = document.getElementById('si-close-btn');
const cancelBtn = document.getElementById('si-cancel-btn');
const saveBtn = document.getElementById('si-save-btn');
const selectorInput = document.getElementById('si-selector-input');
const hiddenCheck = document.getElementById('si-hidden-check');
const colorPicker = document.getElementById('si-color-picker');
const bgPicker = document.getElementById('si-bg-picker');
const fontSizeSlider = document.getElementById('si-font-size');
const paddingSlider = document.getElementById('si-padding');
const widthSlider = document.getElementById('si-width');
const heightSlider = document.getElementById('si-height');
const radiusSlider = document.getElementById('si-radius');
const fontSizeInput = document.getElementById('si-font-size-input');
const paddingInput = document.getElementById('si-padding-input');
const widthInput = document.getElementById('si-width-input');
const heightInput = document.getElementById('si-height-input');
const radiusInput = document.getElementById('si-radius-input');
const customCssInput = document.getElementById('si-custom-css');
// 确保元素都加载到了
const safeGetValue = (el, fallback = 0) => el ? parseInt(el.value) || fallback : fallback;
// 读取当前样式
const computedStyle = window.getComputedStyle(targetEl);
colorPicker.value = rgbToHex(computedStyle.color);
bgPicker.value = rgbToHex(computedStyle.backgroundColor);
const currentFontSize = parseInt(computedStyle.fontSize) || 16;
fontSizeSlider.value = currentFontSize;
fontSizeInput.value = currentFontSize;
const currentPadding = parseInt(computedStyle.padding) || 0;
paddingSlider.value = currentPadding;
paddingInput.value = currentPadding;
// 宽高计算
const currentWidth = parseInt(computedStyle.width) || 0;
let parentWidth = window.innerWidth;
if (targetEl.parentElement && targetEl.parentElement.clientWidth > 0) {
parentWidth = targetEl.parentElement.clientWidth;
} else if (targetEl === document.documentElement) {
// 如果选中了 html 元素
parentWidth = window.innerWidth;
}
let currentWidthPercent = 100;
if (currentWidth > 0) {
currentWidthPercent = Math.round((currentWidth / parentWidth) * 100);
}
// 限制在 0-100 之间
currentWidthPercent = Math.min(100, Math.max(0, currentWidthPercent));
widthSlider.value = currentWidthPercent;
widthInput.value = currentWidthPercent;
const currentHeight = parseInt(computedStyle.height) || 0;
heightSlider.max = Math.max(1000, currentHeight * 2);
heightSlider.value = currentHeight;
heightInput.value = currentHeight;
const currentRadius = parseInt(computedStyle.borderRadius) || 0;
radiusSlider.value = currentRadius;
radiusInput.value = currentRadius;
// 创建预览用的 Style 标签
let previewStyleEl = document.getElementById('si-preview-style');
if (!previewStyleEl) {
previewStyleEl = document.createElement('style');
previewStyleEl.id = 'si-preview-style';
document.head.appendChild(previewStyleEl);
}
// 核心函数:根据当前控件状态生成 CSS
const generateCss = () => {
let css = '';
if (hiddenCheck.checked) {
css = 'display: none !important;';
} else {
const safeVal = (input) => (input && input.value !== '') ? input.value : 0;
css += `color: ${colorPicker.value} !important; `;
css += `background-color: ${bgPicker.value} !important; `;
css += `font-size: ${safeVal(fontSizeInput)}px !important; `;
css += `padding: ${safeVal(paddingInput)}px !important; `;
css += `width: ${safeVal(widthInput)}% !important; `;
css += `height: ${safeVal(heightInput)}px !important; `;
css += `border-radius: ${safeVal(radiusInput)}px !important; `;
if (customCssInput.value) {
css += customCssInput.value;
}
}
return css;
};
// 实时预览函数
const updatePreview = (source) => {
// 1. 同步数值:Slider <-> Input
if (source === 'slider') {
fontSizeInput.value = fontSizeSlider.value;
paddingInput.value = paddingSlider.value;
widthInput.value = widthSlider.value;
heightInput.value = heightSlider.value;
radiusInput.value = radiusSlider.value;
} else if (source === 'input') {
fontSizeSlider.value = fontSizeInput.value;
paddingSlider.value = paddingInput.value;
widthSlider.value = widthInput.value;
heightSlider.value = heightInput.value;
radiusSlider.value = radiusInput.value;
}
// 2. 生成并注入 CSS
const currentSelector = selectorInput.value.trim() || selector;
const css = generateCss();
previewStyleEl.textContent = `${currentSelector} { ${css} }`;
};
// 绑定监听器 - Slider
hiddenCheck.addEventListener('change', () => updatePreview('slider'));
colorPicker.addEventListener('input', () => updatePreview('slider'));
bgPicker.addEventListener('input', () => updatePreview('slider'));
fontSizeSlider.addEventListener('input', () => updatePreview('slider'));
paddingSlider.addEventListener('input', () => updatePreview('slider'));
widthSlider.addEventListener('input', () => updatePreview('slider'));
heightSlider.addEventListener('input', () => updatePreview('slider'));
radiusSlider.addEventListener('input', () => updatePreview('slider'));
customCssInput.addEventListener('input', () => updatePreview('slider'));
selectorInput.addEventListener('input', () => updatePreview('slider'));
// 绑定监听器 - Input
fontSizeInput.addEventListener('input', () => updatePreview('input'));
paddingInput.addEventListener('input', () => updatePreview('input'));
widthInput.addEventListener('input', () => updatePreview('input'));
heightInput.addEventListener('input', () => updatePreview('input'));
radiusInput.addEventListener('input', () => updatePreview('input'));
// 按钮事件
const closeAction = () => {
if (previewStyleEl) previewStyleEl.remove();
closeEditor();
};
closeBtn.addEventListener('click', closeAction);
cancelBtn.addEventListener('click', closeAction);
saveBtn.addEventListener('click', () => {
const finalSelector = selectorInput.value.trim() || selector;
const finalCss = generateCss();
// 注意:不要立即移除预览样式,否则会导致样式闪烁(先恢复原样再应用新样式)
// 我们将 previewStyleEl 的清理交给 saveRule 的回调,或者让页面刷新/重载覆盖
saveRule(finalSelector, finalCss, () => {
// 样式已保存并重新应用,现在可以安全移除预览样式了
if (previewStyleEl) previewStyleEl.remove();
showToast('样式已保存');
});
closeEditor();
});
}
function closeEditor() {
if (editorEl) {
editorEl.remove();
editorEl = null;
}
}
// ------ 辅助功能 ------
function getUniqueSelector(el) {
if (el.id) return '#' + el.id;
if (el === document.body) return 'body';
let path = [];
while (el.parentNode) {
let tag = el.tagName.toLowerCase();
let siblings = el.parentNode.children;
if (el.className && typeof el.className === 'string' && el.className.trim() !== '') {
// 简化:只取第一个class
const firstClass = el.className.split(' ')[0];
if (firstClass) tag += '.' + firstClass;
}
if (siblings.length > 1) {
let index = Array.prototype.indexOf.call(siblings, el) + 1;
tag += ':nth-child(' + index + ')';
}
path.unshift(tag);
el = el.parentNode;
if (el.id) {
path.unshift('#' + el.id);
break;
}
if (el === document.body) {
path.unshift('body');
break;
}
}
return path.join(' > ');
}
function rgbToHex(rgb) {
if (!rgb || rgb === 'rgba(0, 0, 0, 0)') return '#ffffff';
if (rgb.startsWith('#')) return rgb;
const rgbMatch = rgb.match(/\d+/g);
if (!rgbMatch) return '#000000';
const r = parseInt(rgbMatch[0]);
const g = parseInt(rgbMatch[1]);
const b = parseInt(rgbMatch[2]);
return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
}
// ...
function saveRule(selector, styles, callback) {
// 构建CSS字符串 (如果是对象形式) - 但这里我们直接传了字符串
let css = '';
if (typeof styles === 'string') {
css = styles;
} else {
// 兼容旧代码
if (styles.display === 'none') {
css += 'display: none !important;';
} else {
css += `color: ${styles.color} !important;`;
css += `background-color: ${styles.backgroundColor} !important;`;
css += `font-size: ${styles.fontSize} !important;`;
}
}
const hostname = window.location.hostname;
chrome.storage.local.get(['styleRules'], (result) => {
const allRules = result.styleRules || {};
const rules = allRules[hostname] || [];
// 查找是否存在相同选择器的规则
const existingIndex = rules.findIndex(r => r.selector === selector);
if (existingIndex !== -1) {
rules[existingIndex].css = css;
} else {
rules.push({ selector, css });
}
allRules[hostname] = rules;
chrome.storage.local.set({ styleRules: allRules }, () => {
loadAndApplyRules(); // 重新应用所有规则
if (callback) callback();
});
});
}
function loadAndApplyRules() {
const hostname = window.location.hostname;
chrome.storage.local.get(['styleRules'], (result) => {
const allRules = result.styleRules || {};
// 如果没有规则,默认为空数组,以便 applyStyles 能执行并清空样式
const rules = allRules[hostname] || [];
applyStyles(rules);
});
}
function applyStyles(rules) {
const styleId = 'style-injector-css';
let styleEl = document.getElementById(styleId);
if (!styleEl) {
styleEl = document.createElement('style');
styleEl.id = styleId;
document.head.appendChild(styleEl);
}
let css = '';
rules.forEach(rule => {
css += `${rule.selector} { ${rule.css} }\n`;
});
styleEl.textContent = css;
}
function clearAllRules() {
const hostname = window.location.hostname;
chrome.storage.local.get(['styleRules'], (result) => {
const allRules = result.styleRules || {};
delete allRules[hostname];
chrome.storage.local.set({ styleRules: allRules }, () => {
loadAndApplyRules(); // 清空样式
showToast('已清除');
});
});
}
function showToast(msg) {
const toast = document.createElement('div');
toast.textContent = msg;
toast.style.cssText = `
position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%);
background: rgba(0,0,0,0.8); color: white; padding: 10px 20px;
border-radius: 20px; font-size: 14px; z-index: 2147483647;
`;
document.body.appendChild(toast);
setTimeout(() => toast.remove(), 3000);
}