-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
36 lines (28 loc) · 1.35 KB
/
background.js
File metadata and controls
36 lines (28 loc) · 1.35 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
// background.js
chrome.action.onClicked.addListener(async (tab) => {
// 检查是否在受限页面
if (!tab.url || tab.url.startsWith("chrome://") || tab.url.startsWith("edge://") || tab.url.startsWith("about:")) {
console.warn("Cannot run extension on this page.");
return;
}
try {
// 尝试发送一个 ping 消息来检测 content script 是否存在
const response = await chrome.tabs.sendMessage(tab.id, { action: "ping" }).catch(() => null);
if (!response) {
console.log("Content script not detected (likely opened before extension install). Injecting scripts...");
// 主动注入脚本
// 注意:我们不需要注入 CSS 到主文档,因为 content.js 会在 Shadow DOM 中加载 CSS
await chrome.scripting.executeScript({
target: { tabId: tab.id },
files: ["readability.js", "content.js"]
});
console.log("Scripts injected successfully.");
// 给一点时间让脚本初始化
await new Promise(resolve => setTimeout(resolve, 100));
}
// 发送切换命令
chrome.tabs.sendMessage(tab.id, { action: "toggleReadingMode" });
} catch (err) {
console.error("Failed to execute content script:", err);
}
});