1、并发进行脚本注入
2、完善过滤逻辑
This commit is contained in:
雨霖铃
2026-02-07 00:31:41 +08:00
parent 2c0df95104
commit a94ae7421e
+32 -15
View File
@@ -15,23 +15,40 @@ export default defineBackground(() => {
console.log('Extension updated to a new version'); console.log('Extension updated to a new version');
} }
// 给所有已打开的标签页注入 content script // 获取所有标签页
for (const tab of await browser.tabs.query({})) { const tabs = await browser.tabs.query({});
if (tab.url?.match(/(chrome|chrome-extension):\/\//gi) || !tab.id) {
continue;
}
// 注入 content script // 过滤不合法或受限制的 URL
try { const targetTabs = tabs.filter((tab) => {
const res = await browser.scripting.executeScript({ if (!tab.id || !tab.url) return false;
target: { tabId: tab.id }, // 过滤掉浏览器内部页面和不支持注入的协议
files: ['/content-scripts/content.js'], const restrictedProtocols = [
'chrome:',
'chrome-extension:',
'about:',
'edge:',
'view-source:',
];
return !restrictedProtocols.some((protocol) => tab.url!.startsWith(protocol));
}); });
console.log('Content script injected on installed/updated:', res);
} catch (error) { const results = await Promise.allSettled(
console.error('Failed to inject content script:', error); targetTabs.map((tab) =>
} browser.scripting
} .executeScript({
target: { tabId: tab.id! },
files: ['/content-scripts/content.js'],
})
.catch((err) => {
console.warn(`Failed to inject script into tab ${tab.id}:`, err.message);
}),
),
);
const successCount = results.filter((r) => r.status === 'fulfilled').length;
console.log(
`Successfully injected content script into ${successCount}/${targetTabs.length} tabs.`,
);
}); });
// 监听来自 popup script 的消息 // 监听来自 popup script 的消息