-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
553 lines (463 loc) · 18.2 KB
/
Copy pathbackground.js
File metadata and controls
553 lines (463 loc) · 18.2 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
// 任务状态枚举
const TASK_STATUS = {
IDLE: 'idle',
RUNNING: 'running',
PAUSED: 'paused',
COMPLETED: 'completed',
FAILED: 'failed'
};
// 辅助函数:获取 URL 的 origin
function getOrigin(url) {
if (!url) return '';
try {
const urlObj = new URL(url);
return urlObj.origin;
} catch (e) {
return '';
}
}
// 初始化:监听安装
chrome.runtime.onInstalled.addListener(() => {
chrome.storage.local.set({
currentTask: null, // 当前任务对象 { id, steps, currentIndex, status, targetUrl }
taskLog: [],
recordedActions: [], // 录制的动作列表(兼容旧版本)
isRecording: false, // 录制状态
flows: [], // 多流程列表 [{id, name, steps, schedule, createdAt, lastRunAt}]
currentFlowId: null, // 当前选中的流程ID
lastRecordedTab: null // 最后记录的 Tab 信息 {tabId, url, title}
});
// 自动打开侧边栏
chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true });
});
// 监听来自 Popup 或 Content 的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
handle_message(request, sender, sendResponse);
return true; // 保持异步响应
});
async function handle_message(request, sender, sendResponse) {
const { type, payload } = request;
if (type === 'START_TASK') {
await startTask(payload.steps);
sendResponse({ success: true });
}
else if (type === 'STEP_COMPLETED') {
// 某一步执行成功,推进队列
await nextStep();
sendResponse({ success: true });
}
else if (type === 'STEP_FAILED') {
// 执行失败,记录日志并暂停任务
const stepIndex = payload?.stepIndex || 0;
const error = payload?.error || 'Unknown error';
// 暂停任务
const storage = await chrome.storage.local.get(['currentTask']);
let task = storage.currentTask;
if (task) {
task.status = TASK_STATUS.PAUSED;
task.endTime = Date.now();
await chrome.storage.local.set({ currentTask: task });
console.log('[Background] 任务因步骤失败而暂停');
}
await logError(stepIndex + 1, error); // 步骤编号从1开始
sendResponse({ success: true });
}
else if (type === 'KEEP_ALIVE') {
// 心跳包,防止 SW 休眠
sendResponse({ status: 'alive' });
}
else if (type === 'GET_TASK_STATUS') {
const data = await chrome.storage.local.get(['currentTask']);
sendResponse(data.currentTask || { status: TASK_STATUS.IDLE });
}
else if (type === 'SAVE_ACTION') {
// 保存录制的动作
const action = payload || request.action;
if (!action) {
console.error('[Background] SAVE_ACTION 消息格式错误:', request);
sendResponse({ success: false, error: 'Missing action data' });
return;
}
// 获取当前 Tab 信息
let tabInfo = null;
if (sender.tab) {
tabInfo = {
tabId: sender.tab.id,
url: sender.tab.url,
title: sender.tab.title
};
}
const storage = await chrome.storage.local.get(['recordedActions', 'currentFlowId', 'flows', 'lastRecordedTab']);
let actions = storage.recordedActions || [];
const lastRecordedTab = storage.lastRecordedTab || null;
// 智能检测网页切换
let needNavigateAction = false;
if (tabInfo) {
// 检查是否切换了网页(通过 tabId 和 URL 的 origin 判断)
if (!lastRecordedTab ||
lastRecordedTab.tabId !== tabInfo.tabId ||
getOrigin(lastRecordedTab.url) !== getOrigin(tabInfo.url)) {
needNavigateAction = true;
console.log('[Background] 检测到网页切换,需要添加导航指令');
console.log('[Background] 上一个 Tab:', lastRecordedTab);
console.log('[Background] 当前 Tab:', tabInfo);
}
}
// 如果需要,先添加导航指令
if (needNavigateAction && tabInfo) {
const navigateAction = {
type: 'navigate',
url: tabInfo.url,
title: tabInfo.title,
tabId: tabInfo.tabId,
timestamp: Date.now()
};
// 检查最后一个动作是否已经是相同的导航指令
const lastAction = actions[actions.length - 1];
const isLastNavigate = lastAction &&
lastAction.type === 'navigate' &&
getOrigin(lastAction.url) === getOrigin(navigateAction.url);
if (!isLastNavigate) {
actions.push(navigateAction);
console.log('[Background] 添加导航指令:', navigateAction);
await logMessage(`打开网页: ${tabInfo.title || tabInfo.url}`);
}
// 更新最后记录的 Tab 信息
await chrome.storage.local.set({ lastRecordedTab: tabInfo });
}
// 检查是否是重复动作
const lastAction = actions[actions.length - 1];
if (lastAction) {
const isDuplicate = (
lastAction.type === action.type &&
lastAction.selector === action.selector &&
lastAction.value === action.value &&
Math.abs(lastAction.timestamp - action.timestamp) < 100
);
if (isDuplicate) {
console.log('[Background] 检测到重复动作,忽略:', action);
sendResponse({ success: true });
return;
}
}
// 为动作添加 Tab 信息(但不包含完整 URL,只保留 origin)
if (tabInfo) {
action.tabId = tabInfo.tabId;
action.pageOrigin = getOrigin(tabInfo.url);
action.pageTitle = tabInfo.title;
}
actions.push(action);
await chrome.storage.local.set({ recordedActions: actions });
// 如果有当前流程ID,也更新到对应流程的steps中
if (storage.currentFlowId && storage.flows) {
const flows = storage.flows;
const flowIndex = flows.findIndex(f => f.id === storage.currentFlowId);
if (flowIndex !== -1) {
flows[flowIndex].steps = [...actions];
flows[flowIndex].updatedAt = Date.now();
await chrome.storage.local.set({ flows: flows });
}
}
// 添加到任务日志
let actionDesc = '';
if (action.type === 'click') {
actionDesc = `点击: ${action.tagName} (${action.selector})`;
} else if (action.type === 'type') {
actionDesc = `输入: ${action.value} (${action.selector})`;
} else if (action.type === 'wait') {
actionDesc = `等待: ${action.duration}ms`;
}
await logMessage(`录制动作: ${actionDesc}`);
console.log('[Background] 保存动作成功:', action);
sendResponse({ success: true });
}
else if (type === 'GET_ACTIONS') {
const storage = await chrome.storage.local.get(['recordedActions']);
sendResponse(storage.recordedActions || []);
}
else if (type === 'GET_FLOWS') {
const storage = await chrome.storage.local.get(['flows']);
sendResponse(storage.flows || []);
}
else if (type === 'CREATE_FLOW') {
const flowName = payload?.name || '新流程';
const newFlow = {
id: Date.now().toString(),
name: flowName,
steps: [],
schedule: null,
createdAt: Date.now(),
updatedAt: Date.now(),
lastRunAt: null
};
const storage = await chrome.storage.local.get(['flows']);
const flows = storage.flows || [];
flows.push(newFlow);
await chrome.storage.local.set({ flows: flows, currentFlowId: newFlow.id, recordedActions: [] });
await logMessage(`创建流程: ${flowName}`);
sendResponse({ success: true, flow: newFlow });
}
else if (type === 'SELECT_FLOW') {
const flowId = payload?.flowId;
if (!flowId) {
sendResponse({ success: false, error: 'Missing flowId' });
return;
}
const storage = await chrome.storage.local.get(['flows']);
const flows = storage.flows || [];
const flow = flows.find(f => f.id === flowId);
if (flow) {
await chrome.storage.local.set({ currentFlowId: flowId, recordedActions: flow.steps || [] });
sendResponse({ success: true, flow: flow });
} else {
sendResponse({ success: false, error: 'Flow not found' });
}
}
else if (type === 'UPDATE_FLOW') {
const { flowId, updates } = payload;
if (!flowId) {
sendResponse({ success: false, error: 'Missing flowId' });
return;
}
const storage = await chrome.storage.local.get(['flows']);
const flows = storage.flows || [];
const flowIndex = flows.findIndex(f => f.id === flowId);
if (flowIndex !== -1) {
flows[flowIndex] = { ...flows[flowIndex], ...updates, updatedAt: Date.now() };
await chrome.storage.local.set({ flows: flows });
const currentStorage = await chrome.storage.local.get(['currentFlowId']);
if (currentStorage.currentFlowId === flowId) {
await chrome.storage.local.set({ recordedActions: flows[flowIndex].steps || [] });
}
sendResponse({ success: true, flow: flows[flowIndex] });
} else {
sendResponse({ success: false, error: 'Flow not found' });
}
}
else if (type === 'DELETE_FLOW') {
const flowId = payload?.flowId;
if (!flowId) {
sendResponse({ success: false, error: 'Missing flowId' });
return;
}
const storage = await chrome.storage.local.get(['flows', 'currentFlowId']);
let flows = storage.flows || [];
const flowIndex = flows.findIndex(f => f.id === flowId);
if (flowIndex !== -1) {
const deletedFlow = flows[flowIndex];
flows.splice(flowIndex, 1);
let newCurrentFlowId = storage.currentFlowId;
if (newCurrentFlowId === flowId) {
newCurrentFlowId = flows.length > 0 ? flows[0].id : null;
await chrome.storage.local.set({ recordedActions: newCurrentFlowId ? flows[0].steps : [] });
}
await chrome.storage.local.set({ flows: flows, currentFlowId: newCurrentFlowId });
await logMessage(`删除流程: ${deletedFlow.name}`);
sendResponse({ success: true });
} else {
sendResponse({ success: false, error: 'Flow not found' });
}
}
else if (type === 'CLEAR_ACTIONS') {
await chrome.storage.local.set({ recordedActions: [] });
sendResponse({ success: true });
}
else if (type === 'TOGGLE_RECORDING') {
const storage = await chrome.storage.local.get(['isRecording']);
const currentStatus = storage.isRecording || false;
const newStatus = !currentStatus;
await chrome.storage.local.set({ isRecording: newStatus });
console.log('[Background] 录制状态已切换:', currentStatus, '->', newStatus);
await logMessage(`录制状态: ${newStatus ? '开始' : '停止'}`);
if (newStatus) {
// 开始录制时,清空上次记录的 Tab 信息
await chrome.storage.local.set({ lastRecordedTab: null });
const tabs = await chrome.tabs.query({});
for (const tab of tabs) {
try {
await chrome.tabs.sendMessage(tab.id, { type: 'TOGGLE_RECORDING', status: true });
console.log(`[Background] 已通知 Tab ${tab.id} 开始录制`);
} catch (e) {
console.warn(`[Background] 无法通知 Tab ${tab.id} 开始录制:`, e);
}
}
} else {
const tabs = await chrome.tabs.query({});
for (const tab of tabs) {
try {
await chrome.tabs.sendMessage(tab.id, { type: 'TOGGLE_RECORDING', status: false });
console.log(`[Background] 已通知 Tab ${tab.id} 停止录制`);
} catch (e) {
console.warn(`[Background] 无法通知 Tab ${tab.id} 停止录制:`, e);
}
}
// 停止录制时,清空上次记录的 Tab 信息
await chrome.storage.local.set({ lastRecordedTab: null });
}
sendResponse({ status: newStatus });
}
else if (type === 'STOP_TASK') {
await stopTask();
sendResponse({ success: true });
}
}
// 启动任务
async function startTask(steps) {
const taskId = Date.now().toString();
const task = {
id: taskId,
steps: steps,
currentIndex: 0,
status: TASK_STATUS.RUNNING,
startTime: Date.now(),
lastActiveTabId: null
};
await chrome.storage.local.set({ currentTask: task, taskLog: [`任务 ${taskId} 启动,共 ${steps.length} 步`] });
console.log(`[Scheduler] 任务 ${taskId} 开始`);
executeCurrentStep(task);
}
// 执行当前步骤
async function executeCurrentStep(taskData) {
const storage = await chrome.storage.local.get(['currentTask']);
let task = storage.currentTask;
if (!task || task.status !== TASK_STATUS.RUNNING) return;
if (task.currentIndex >= task.steps.length) {
await finishTask(task, true);
return;
}
const step = task.steps[task.currentIndex];
try {
if (step.waitBefore && step.waitBefore > 0) {
console.log(`[Scheduler] 执行前等待 ${step.waitBefore}ms`);
await logMessage(`步骤 ${task.currentIndex + 1} 执行前等待 ${step.waitBefore}ms`);
await new Promise(resolve => setTimeout(resolve, step.waitBefore));
}
if (step.type === 'navigate') {
console.log('[Scheduler] 执行 navigate 操作:', step.url);
// 查找是否已有相同 origin 的 Tab
const tabs = await chrome.tabs.query({});
const targetOrigin = getOrigin(step.url);
let existingTab = tabs.find(tab => tab.url && getOrigin(tab.url) === targetOrigin);
if (existingTab) {
// 如果已有相同 origin 的 Tab,激活并导航
await chrome.tabs.update(existingTab.id, { active: true, url: step.url });
await logMessage(`激活并导航到: ${step.title || step.url}`);
// 等待页面加载完成
await new Promise(resolve => {
chrome.tabs.onUpdated.addListener(function listener(tabId, changeInfo) {
if (tabId === existingTab.id && changeInfo.status === 'complete') {
chrome.tabs.onUpdated.removeListener(listener);
resolve();
}
});
});
task.lastActiveTabId = existingTab.id;
} else {
// 否则创建新 Tab
const newTab = await chrome.tabs.create({ url: step.url, active: true });
await logMessage(`打开新网页: ${step.title || step.url}`);
// 等待页面加载完成
await new Promise(resolve => {
chrome.tabs.onUpdated.addListener(function listener(tabId, changeInfo) {
if (tabId === newTab.id && changeInfo.status === 'complete') {
chrome.tabs.onUpdated.removeListener(listener);
resolve();
}
});
});
task.lastActiveTabId = newTab.id;
}
await chrome.storage.local.set({ currentTask: task });
await nextStep();
return;
}
// 对于 click 和 type 操作,使用当前活动的 Tab
let tab;
if (task.lastActiveTabId) {
try {
tab = await chrome.tabs.get(task.lastActiveTabId);
console.log('[Scheduler] 使用上次活动的 Tab:', tab.id);
} catch (e) {
console.warn('[Scheduler] 上次活动的 Tab 不存在,使用当前活动 Tab');
const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
tab = tabs[0];
}
} else {
const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
tab = tabs[0];
}
if (!tab) {
console.error('[Scheduler] 无法找到活动的 Tab');
await logError(task.currentIndex + 1, '无法找到活动的 Tab');
task.status = TASK_STATUS.PAUSED;
task.endTime = Date.now();
await chrome.storage.local.set({ currentTask: task });
return;
}
task.lastActiveTabId = tab.id;
await chrome.storage.local.set({ currentTask: task });
console.log('[Scheduler] 发送执行指令到 Tab:', tab.id, '步骤:', step);
chrome.tabs.sendMessage(tab.id, {
type: 'EXECUTE_STEP',
step: step,
taskIndex: task.currentIndex
}, (response) => {
if (chrome.runtime.lastError) {
console.error('[Scheduler] 发送失败:', chrome.runtime.lastError);
console.warn('[Scheduler] 等待页面加载后重试...');
chrome.tabs.onUpdated.addListener(function listener(tabId, changeInfo) {
if (tabId === tab.id && changeInfo.status === 'complete') {
chrome.tabs.onUpdated.removeListener(listener);
console.log('[Scheduler] Tab 加载完成,重试发送指令');
setTimeout(() => executeCurrentStep(task), 500);
}
});
setTimeout(() => executeCurrentStep(task), 3000);
} else {
console.log('[Scheduler] 发送成功,等待步骤完成');
}
});
} catch (error) {
console.error('[Scheduler] 执行出错:', error);
await logError(task.currentIndex + 1, error.message);
task.status = TASK_STATUS.PAUSED;
task.endTime = Date.now();
await chrome.storage.local.set({ currentTask: task });
console.log('[Background] 任务因执行出错而暂停');
}
}
async function nextStep() {
const storage = await chrome.storage.local.get(['currentTask']);
let task = storage.currentTask;
if (!task) return;
task.currentIndex++;
await chrome.storage.local.set({ currentTask: task });
executeCurrentStep(task);
}
async function finishTask(task, success) {
task.status = success ? TASK_STATUS.COMPLETED : TASK_STATUS.FAILED;
task.endTime = Date.now();
await chrome.storage.local.set({ currentTask: task });
await logMessage(`任务结束:${success ? '成功' : '失败'}`);
console.log(`[Scheduler] 任务 ${task.id} 结束`);
}
async function logMessage(msg) {
const storage = await chrome.storage.local.get(['taskLog']);
const logs = storage.taskLog || [];
logs.push(`[${new Date().toLocaleTimeString()}] ${msg}`);
if (logs.length > 50) logs.shift();
await chrome.storage.local.set({ taskLog: logs });
}
async function logError(index, error) {
await logMessage(`步骤 ${index} 出错:${error},任务已暂停`);
}
async function stopTask() {
const storage = await chrome.storage.local.get(['currentTask']);
const task = storage.currentTask;
if (!task) return;
task.status = TASK_STATUS.PAUSED;
task.endTime = Date.now();
await chrome.storage.local.set({ currentTask: task });
await logMessage(`任务已停止,当前进度:${task.currentIndex}/${task.steps.length}`);
console.log(`[Scheduler] 任务 ${task.id} 已停止`);
}