-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
351 lines (302 loc) · 12.1 KB
/
Copy pathcontent.js
File metadata and controls
351 lines (302 loc) · 12.1 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
// 创建悬浮窗口函数
function createFloatingWindow() {
const container = document.createElement('div');
container.id = 'xpath-analyzer-container';
// 读取本地存储的主题偏好
const isGlassTheme = localStorage.getItem('xpath-glass-theme') === 'true';
if (isGlassTheme) {
container.classList.add('glass-effect');
}
// 修改 HTML
container.innerHTML = `
<div class="xpath-header" style="display: flex; justify-content: space-between; align-items: center; padding-right: 10px;">
<div style="display: flex; align-items: center;">
<h4 style="color: #ffffff; margin: 0; font-size: 14px; font-weight: 600; letter-spacing: 0.5px;">XPATH Parser v1.2</h4>
<!-- 主题切换开关 -->
<div class="theme-switch-wrapper" title="Switch Theme">
<label class="theme-switch">
<input type="checkbox" id="theme-toggle" ${isGlassTheme ? 'checked' : ''}>
<span class="slider round"></span>
</label>
</div>
</div>
<!-- 关闭按钮:CSS会把它变成圆形 -->
<button class="close-button">×</button>
</div>
<div class="xpath-content">
<div class="xpath-input-section">
<textarea id="xpath-input" placeholder="Please input XPATH expression..."></textarea>
<div class="button-group">
<button id="clear-btn">Clear</button>
<button id="parse-btn">Parse</button>
</div>
</div>
<div class="xpath-result-section">
<div class="result-header" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
<span class="result-count">Result (0 rows)</span>
<div class="copy-buttons">
<!-- 去掉了内联样式,让 CSS 控制它的外观 -->
<button id="copy-format-btn">Copy Result</button>
</div>
</div>
<div id="result-container"></div>
</div>
</div>
`;
document.body.appendChild(container);
// 设置初始位置在窗口中央
const initialLeft = (window.innerWidth - container.offsetWidth) / 2;
const initialTop = 100;
container.style.left = `${initialLeft}px`;
container.style.top = `${initialTop}px`;
// 3. 绑定主题切换事件
const themeToggle = container.querySelector('#theme-toggle');
themeToggle.addEventListener('change', (e) => {
if (e.target.checked) {
container.classList.add('glass-effect');
localStorage.setItem('xpath-glass-theme', 'true'); // 保存偏好
} else {
container.classList.remove('glass-effect');
localStorage.setItem('xpath-glass-theme', 'false'); // 保存偏好
}
});
// 添加拖动功能
let isDragging = false;
let currentX;
let currentY;
let initialX;
let initialY;
let xOffset = initialLeft;
let yOffset = initialTop;
const header = container.querySelector('.xpath-header');
header.addEventListener('mousedown', dragStart);
document.addEventListener('mousemove', drag);
document.addEventListener('mouseup', dragEnd);
function dragStart(e) {
// 防止点击开关时触发拖拽
if (e.target.closest('.theme-switch') || e.target.closest('.close-button')) {
return;
}
if (e.target.closest('.xpath-header')) {
initialX = e.clientX - xOffset;
initialY = e.clientY - yOffset;
isDragging = true;
container.classList.add('dragging');
}
}
function drag(e) {
if (isDragging) {
e.preventDefault();
currentX = e.clientX - initialX;
currentY = e.clientY - initialY;
xOffset = currentX;
yOffset = currentY;
const maxX = window.innerWidth - container.offsetWidth;
const maxY = window.innerHeight - container.offsetHeight;
if (currentX < 0) currentX = 0;
if (currentX > maxX) currentX = maxX;
if (currentY < 0) currentY = 0;
if (currentY > maxY) currentY = maxY;
setTranslate(currentX, currentY);
}
}
function dragEnd() {
if (isDragging) {
initialX = currentX;
initialY = currentY;
isDragging = false;
container.classList.remove('dragging');
}
}
function setTranslate(xPos, yPos) {
container.style.left = `${xPos}px`;
container.style.top = `${yPos}px`;
}
// 绑定其他事件处理
const closeBtn = container.querySelector('.close-button');
const clearBtn = container.querySelector('#clear-btn');
const parseBtn = container.querySelector('#parse-btn');
const xpathInput = container.querySelector('#xpath-input');
if (closeBtn) {
closeBtn.addEventListener('click', () => {
container.classList.remove('visible');
});
}
// 修改清空按钮事件处理
if (clearBtn) {
clearBtn.addEventListener('click', () => {
xpathInput.value = '';
document.querySelector('#result-container').innerHTML = '';
// 只更新计数文本,不影响按钮
const resultCount = document.querySelector('.result-count');
resultCount.textContent = 'Result (0 rows)';
});
}
if (parseBtn) {
parseBtn.addEventListener('click', () => {
const xpath = xpathInput.value;
if (xpath.trim()) {
evaluateXPath(xpath, document.querySelector('#result-container'));
}
});
}
// 复制功能 - 添加定时器ID跟踪
let copyTimeoutId = null;
// 复制带格式功能(保留HTML结构)
function handleCopyFormat() {
const resultContainer = document.querySelector('#result-container');
let formattedText = '';
// 创建格式化的文本,保留层次结构
const resultItems = Array.from(resultContainer.querySelectorAll('.result-item'));
resultItems.forEach((item, index) => {
const textElement = item.querySelector('.result-text');
const text = textElement.textContent;
// 添加内容
formattedText += `${text}\n`;
// 如果有多行内容,额外处理
if (text.includes('\n')) {
const lines = text.split('\n');
lines.forEach((line, lineIndex) => {
if (lineIndex > 0) {
formattedText += ` ${line}\n`;
}
});
}
});
// 移除最后的换行符
formattedText = formattedText.trim();
navigator.clipboard.writeText(formattedText).then(() => {
showCopyMessage('copied!');
}).catch(err => {
console.error('Copy failed: ', err);
alert('Copy failed. Please copy manually.');
});
}
// 显示复制成功消息
function showCopyMessage(message) {
// 移除任何现有提示
const existingMsg = document.querySelector('.copy-success');
if (existingMsg) existingMsg.remove();
// 创建成功提示元素
const successMsg = document.createElement('span');
successMsg.className = 'copy-success';
successMsg.textContent = message;
// 添加到按钮容器
const buttonContainer = container.querySelector('.copy-buttons');
buttonContainer.appendChild(successMsg);
// 3秒后自动移除
setTimeout(() => successMsg.remove(), 3000);
}
// 绑定复制按钮事件
const copyFormatBtn = container.querySelector('#copy-format-btn');
if (copyFormatBtn) {
copyFormatBtn.addEventListener('click', handleCopyFormat);
}
// 修改关闭按钮处理函数
function handleClose() {
// 清除复制按钮的定时器
if (copyTimeoutId) {
clearTimeout(copyTimeoutId);
copyTimeoutId = null; // 显式设为null
}
container.classList.remove('visible');
// 确保消息发送成功
chrome.runtime.sendMessage({action: 'windowClosed'}, (response) => {
if (!response) console.error('Failed to notify window closed');
});
}
return container; // ✅ 将return移到最后
}
// XPATH 解析函数
function evaluateXPath(xpath, resultContainer) {
try {
const processedXpath = xpath.replace(/\[\*\]/g, '[position()]');
const result = document.evaluate(
processedXpath,
document,
null,
XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
null
);
displayResult(result, resultContainer);
} catch (e) {
resultContainer.innerHTML = `<p class="error">错误:${e.message}</p>`;
// 错误时更新结果数量
const resultCount = document.querySelector('.result-count');
resultCount.textContent = 'Result (0 rows)';
}
}
// 修改显示结果函数
function displayResult(result, container) {
container.innerHTML = '';
// 更新结果数量 - 只更新计数文本
const rowCount = result.snapshotLength;
const resultCount = document.querySelector('.result-count');
resultCount.textContent = `Result (${rowCount} rows)`;
if (rowCount === 0) {
container.innerHTML = '<p style="color: var(--text-white);">No matching results found</p>';
return;
}
for (let i = 0; i < rowCount; i++) {
const node = result.snapshotItem(i);
const text = node.textContent.trim() || '';
// 创建结果项容器
const resultItem = document.createElement('div');
resultItem.className = 'result-item';
resultItem.setAttribute('data-index', i + 1);
// 创建文本内容
const textElement = document.createElement('span');
textElement.className = 'result-text';
textElement.textContent = text;
// 组装结果项
resultItem.appendChild(textElement);
// 如果是多行文本,保留换行格式
if (text.includes('\n')) {
textElement.style.whiteSpace = 'pre-line';
textElement.style.display = 'block';
textElement.style.marginLeft = '15px';
}
container.appendChild(resultItem);
}
}
// 获取完整 XPath 路径
function getFullXPath(node) {
if (node.nodeType !== 1) return '';
if (node.hasAttribute('id')) {
return `//*[@id="${node.id}"]`;
}
const sameTagSiblings = Array.from(node.parentNode.children)
.filter(child => child.tagName === node.tagName);
const idx = sameTagSiblings.indexOf(node) + 1;
const path = getFullXPath(node.parentNode);
return path ? `${path}/${node.tagName.toLowerCase()}[${idx}]` : `/${node.tagName.toLowerCase()}[${idx}]`;
}
// 添加消息监听器
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
// 响应ping检查
if (request.action === 'ping') {
sendResponse({ success: true });
}
// 显示窗口(强制显示而非切换)
else if (request.action === 'toggleXPathAnalyzer') {
let container = document.getElementById('xpath-analyzer-container');
if (!container) {
container = createFloatingWindow();
}
container.classList.add('visible'); // 改为强制显示
sendResponse({ success: true });
}
// 销毁窗口
else if (request.action === 'destroyWindow') {
const container = document.getElementById('xpath-analyzer-container');
if (container) {
const copyTimeoutId = container.copyTimeoutId?.();
if (copyTimeoutId) {
clearTimeout(copyTimeoutId);
}
container.remove();
}
sendResponse({ success: true });
}
return true; // 确保异步响应
});