How to load a js function from another file in a chrome plugin (same directory, part of the one the plugin includes)
Assistant
Got it — you’re making a Chrome extension and want to call a JS function that’s defined in another file in the extension’s directory.
Here’s how Chrome extensions handle it:
1️⃣ Manifest-based inclusion
In your manifest.json, you explicitly load the scripts you need:
jsonCopiar código{
"name": "My Extension",
"manifest_version": 3,
"background": {
"service_worker": "background.js"
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["utils.js", "content.js"]
}
]
}
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Here utils.js is loaded first, then content.js. Any functions or variables in utils.js are available to content.js because they’re in the same execution context.
2️⃣ For popup or options pages (HTML)
If you’re adding scripts to your popup or options page, you include them as tags:
htmlCopiar código
Now popup.js can call functions defined in utils.js.
3️⃣ ES Modules (Recommended)
If you’re using Manifest V3, you can also make your scripts ES modules:
jsCopiar código// utils.js
export function myFunction() {
console.log('Hello from utils!');
}
Then in your other script:
jsCopiar código// content.js
import { myFunction } from './utils.js';
myFunction();
But you must declare the file as a module. In your popup HTML:
htmlCopiar código
4️⃣ You can’t dynamically inject scripts into a content script from your extension (MV3)
In MV3, you can’t just importScripts in a content script like in MV2 background pages. Use the ES module approach or include scripts explicitly in the manifest.
Quick summary:
Content scripts: list multiple JS files in the manifest (order matters).
HTML-based pages: add multiple tags in order.
Modern MV3: use type: "module" and import statements.
Do you want me to show a working minimal example of a Chrome extension that uses a function from another file?