-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
107 lines (91 loc) · 3.38 KB
/
Copy pathbackground.js
File metadata and controls
107 lines (91 loc) · 3.38 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
// 后台脚本 - 处理标签页事件和状态管理
// 监听标签页更新事件
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
// 当标签页状态改变时,可以在这里添加额外的逻辑
if (changeInfo.status === 'complete') {
// 标签页加载完成
console.log(`标签页 ${tabId} 加载完成: ${tab.url}`);
}
});
// 监听标签页关闭事件
chrome.tabs.onRemoved.addListener((tabId, removeInfo) => {
console.log(`标签页 ${tabId} 已关闭`);
});
// 监听标签页激活事件
chrome.tabs.onActivated.addListener((activeInfo) => {
console.log(`标签页 ${activeInfo.tabId} 已激活`);
});
// 监听扩展安装事件
chrome.runtime.onInstalled.addListener(() => {
console.log('QuickTab 已安装');
});
// 注意:由于manifest.json中配置了default_popup,
// 扩展图标点击会直接打开popup.html,不会触发onClicked事件
// 监听快捷键命令 - 打开弹窗
chrome.commands.onCommand.addListener(async (command) => {
console.log('🔥 快捷键命令触发:', command);
if (command === 'open_quicktab' || command === 'open_quicktab_alt') {
await openQuickTab();
}
});
// 统一的QuickTab打开函数(用于快捷键触发)
async function openQuickTab() {
console.log('🚀 通过快捷键打开 QuickTab');
try {
// 首先尝试使用标准的popup方式
await chrome.action.openPopup();
console.log('✅ 成功打开弹窗');
return;
} catch (error) {
console.log('⚠️ 标准弹窗打开失败,尝试备选方案:', error.message);
// 如果是"Could not find an active browser window"错误,尝试其他方式
try {
// 检查是否有可用窗口
const windows = await chrome.windows.getAll({
populate: false,
windowTypes: ['normal']
});
if (windows.length === 0) {
// 完全没有窗口,创建一个新的弹窗窗口
await chrome.windows.create({
url: chrome.runtime.getURL('popup.html'),
type: 'popup',
width: 450,
height: 600,
focused: true,
top: 100,
left: 100
});
console.log('✅ 备选方案:创建QuickTab弹窗窗口');
} else {
// 有窗口但无法打开popup,可能所有窗口都最小化了
// 先尝试激活一个窗口,然后再次尝试打开popup
const targetWindow = windows[0];
await chrome.windows.update(targetWindow.id, { focused: true });
// 稍等片刻让窗口激活
setTimeout(async () => {
try {
await chrome.action.openPopup();
console.log('✅ 激活窗口后成功打开弹窗');
} catch (retryError) {
console.log('⚠️ 重试仍失败,使用最终备选方案');
// 最终备选:创建弹窗窗口
await chrome.windows.create({
url: chrome.runtime.getURL('popup.html'),
type: 'popup',
width: 450,
height: 600,
focused: true,
top: 100,
left: 100
});
console.log('✅ 最终备选:创建QuickTab窗口');
}
}, 200);
}
} catch (fallbackError) {
console.error('❌ 所有备选方案都失败了:', fallbackError);
}
}
}
// 现在使用弹窗方式,不需要内容脚本通信