MCPcopy Create free account
hub / github.com/Yorick-Ryu/deep-share / injectContentScriptsOnInstall

Function injectContentScriptsOnInstall

background.js:25–69  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

23
24// Function to dynamically inject content scripts into existing tabs
25async function injectContentScriptsOnInstall() {
26 try {
27 const manifest = chrome.runtime.getManifest();
28 const contentScripts = manifest.content_scripts;
29
30 if (!contentScripts) return;
31
32 for (const script of contentScripts) {
33 const matches = script.matches;
34
35 // Query tabs that match these URLs
36 const tabs = await chrome.tabs.query({ url: matches });
37
38 for (const tab of tabs) {
39 // Ignore empty or restricted URLs
40 if (!tab.url || tab.url.startsWith('chrome://') || tab.url.startsWith('edge://')) {
41 continue;
42 }
43
44 try {
45 // Inject CSS
46 if (script.css && script.css.length > 0) {
47 await chrome.scripting.insertCSS({
48 target: { tabId: tab.id },
49 files: script.css
50 });
51 }
52
53 // Inject JS
54 if (script.js && script.js.length > 0) {
55 await chrome.scripting.executeScript({
56 target: { tabId: tab.id },
57 files: script.js
58 });
59 }
60 console.log(`Successfully injected content scripts into tab ${tab.id} (${tab.url})`);
61 } catch (err) {
62 console.error(`Failed to inject into tab ${tab.id} (${tab.url}):`, err);
63 }
64 }
65 }
66 } catch (e) {
67 console.error('Error during content script injection:', e);
68 }
69}
70
71
72// Listen for messages from content scripts

Callers 1

background.jsFile · 0.85

Calls 1

errorMethod · 0.45

Tested by

no test coverage detected