How to include other scripts

113 views
Skip to first unread message

Joel Saltzman

unread,
Mar 3, 2023, 3:55:13 PM3/3/23
to Chromium Extensions
How should I use export and import in chrome extensions? I'm able to get dynamic imports to load the file, but how should I export?

I have a scripts directory that contains my scripts. The main content script is called content.js. I have allowed access to the other scripts (content_utils.js).
"content_scripts": [
{
"js": [
"scripts/content.js",
"scripts/content_utils.js"
],
"matches": [
"<all_urls>"
]
}
],
"web_accessible_resources": [{
"resources": ["scripts/*", "scripts/*/*"],
"matches": ["<all_urls>"]
}]

// content.js is two lines, import another file and run a function from the file
import(chrome.runtime.getURL('scripts/content_utils.js')) // no errors
echo("something"); // Uncaught ReferenceError: echo is not defined

// content_utils.js - Just an echo function
console.log("Utils loaded!") // This gets logged
function echo(value) {
console.log(`echo being called ${value}`)
return value;
}

export default { echo }; // Uncaught SyntaxError: Unexpected token 'export'


Joel Saltzman

unread,
Mar 3, 2023, 3:59:07 PM3/3/23
to Chromium Extensions, Joel Saltzman
I should also note, I'm hoping to avoid webpack and similar if possible.

Joel Saltzman

unread,
Mar 3, 2023, 5:15:36 PM3/3/23
to Chromium Extensions, Joel Saltzman
I found an example: https://github.com/GoogleChrome/chrome-extensions-samples/blob/5bf419b385860a334a6c2f5c7f0de5ec9a6dcc7b/_archive/mv2/extensions/speak_selection/manifest.json

The order of content_scripts matters and don't use export.

"content_scripts": [
{
"js": [
"scripts/content_utils.js"
"scripts/content.js",
],
"matches": [
"<all_urls>"
]
}
],

// content_utils.js - Just an echo function
console.log("Utils loaded!") // This gets logged
function echo(value) {
console.log(`echo being called ${value}`)
return value;
}

// content.js
echo("something"); // Uncaught ReferenceError: echo is not defined

wOxxOm

unread,
Mar 3, 2023, 5:29:13 PM3/3/23
to Chromium Extensions, Joel Saltzman
To use the dynamic import() correctly:
  1. remove content_utils.js from `content_scripts` in manifest.json
  2. await the result of import (or use `then`) and use the exported symbol explicitly

    import(chrome.runtime.getURL('scripts/content_utils.js')).then(m => {
      m.default.echo('foo');
    });

    // you can also make it global:
    import(chrome.runtime.getURL('scripts/content_utils.js')).then(m => {
      window.echo = m.default.echo;
      echo('foo');
    });

To use multiple files in content_scripts correctly:
  1. remove `export` from content_utils.js
  2. make sure content_utils.js precedes the scripts that use its globals.
In both cases make sure you reload your extension on chrome://extensions page.
Reply all
Reply to author
Forward
0 new messages