-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcontent.js
More file actions
87 lines (68 loc) · 2.93 KB
/
content.js
File metadata and controls
87 lines (68 loc) · 2.93 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
// content.js - Content Script,消息中转
(function() {
'use strict';
console.log('[闲鱼采集] content.js 已加载');
// 初始化消息总线(自动处理所有配置的通道)
if (window.MessageBus && window.MessageBus.init) {
window.MessageBus.init();
} else {
console.error('[闲鱼采集] ❌ MessageBus 未加载');
}
// ==================== 其他 content 功能 ====================
// 监听爬取完成/停止事件(不需要转发给 background,只用于通知 popup)
document.addEventListener('XIANYU_CRAWL_COMPLETED', function() {
console.log('[闲鱼采集] 爬取已完成,通知 popup');
chrome.runtime.sendMessage({ type: 'CRAWL_COMPLETED' });
});
document.addEventListener('XIANYU_CRAWL_STOPPED', function() {
console.log('[闲鱼采集] 爬取已停止,通知 popup');
chrome.runtime.sendMessage({ type: 'CRAWL_STOPPED' });
});
// 监听来自 popup 的扩展消息
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
console.log('[闲鱼采集] Content收到消息:', request.type);
if (request.type === 'START_AUTO_CRAWL') {
console.log('[闲鱼采集] 收到自动爬取指令:', request);
// 转发到页面上下文(通过 DOM 事件)
document.dispatchEvent(new CustomEvent('XIANYU_START_AUTO_CRAWL', {
detail: {
keyword: request.keyword,
startPage: request.startPage,
pageCount: request.pageCount,
delay: request.delay || 1500
}
}));
console.log('[闲鱼采集] 已派发DOM事件 XIANYU_START_AUTO_CRAWL');
sendResponse({ started: true });
return true;
}
if (request.type === 'STOP_AUTO_CRAWL') {
console.log('[闲鱼采集] 收到停止爬取指令');
// 转发到页面上下文
document.dispatchEvent(new CustomEvent('XIANYU_STOP_AUTO_CRAWL'));
console.log('[闲鱼采集] 已派发DOM事件 XIANYU_STOP_AUTO_CRAWL');
sendResponse({ stopped: true });
return true;
}
if (request.type === 'FETCH_SUGGEST_WORDS') {
console.log('[闲鱼采集] 收到流量词请求:', request.keyword);
// 监听来自页面的响应
const handleSuggestResponse = function(event) {
console.log('[闲鱼采集] 收到流量词响应:', event.detail);
document.removeEventListener('XIANYU_SUGGEST_WORDS_RESPONSE', handleSuggestResponse);
sendResponse(event.detail);
};
document.addEventListener('XIANYU_SUGGEST_WORDS_RESPONSE', handleSuggestResponse);
// 转发到页面上下文
document.dispatchEvent(new CustomEvent('XIANYU_FETCH_SUGGEST_WORDS', {
detail: {
keyword: request.keyword
}
}));
console.log('[闲鱼采集] 已派发DOM事件 XIANYU_FETCH_SUGGEST_WORDS');
return true; // 异步响应
}
return true;
});
console.log('[闲鱼采集] Content Script初始化完成');
})();