-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackground.js
84 lines (73 loc) · 1.95 KB
/
background.js
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
/**
* 评论快填 - 后台脚本
*
* @author 時光
* @github https://github.com/shiguang-coding
* @blog https://blog.shiguangdev.cn
*/
// 跟踪已注入脚本的标签页
const injectedTabs = new Set();
// 监听安装事件
chrome.runtime.onInstalled.addListener(function(details) {
// 设置默认值
chrome.storage.sync.get(['nickname', 'email', 'website'], function(data) {
if (!data.nickname || !data.email) {
chrome.storage.sync.set({
nickname: data.nickname || '時光',
email: data.email || '[email protected]',
website: data.website || ''
});
}
});
});
// 注入内容脚本
async function injectContentScript(tabId, url) {
// 检查URL是否合法
if (!url || !url.startsWith('http')) {
return;
}
// 检查脚本是否已注入
try {
const [{ result }] = await chrome.scripting.executeScript({
target: { tabId: tabId },
func: () => window.__COMMENT_AUTOFILL_INJECTED__
});
if (result === true) {
return;
}
} catch (error) {
// 忽略错误,继续注入
}
try {
await chrome.scripting.executeScript({
target: { tabId: tabId },
func: () => {
window.__COMMENT_AUTOFILL_INJECTED__ = true;
}
});
await chrome.scripting.executeScript({
target: { tabId: tabId },
files: ['content.js']
});
injectedTabs.add(tabId);
} catch (error) {
console.error('注入脚本失败:', error);
}
}
// 监听标签页更新
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if (changeInfo.status === 'complete' && tab.url) {
injectContentScript(tabId, tab.url);
}
});
// 监听标签页移除
chrome.tabs.onRemoved.addListener(function(tabId) {
injectedTabs.delete(tabId);
});
// 监听消息
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.type === 'contentScriptLoaded') {
sendResponse({ status: 'ok' });
}
return true;
});