0

I had defined a content script in the manifest.json as:

    "content_scripts": [
        {
            "matches": [
                "https://*/*"
            ],
            "js": [
                "cs.js"
            ]
        }
    ]

And in cs.js I would like to load another JS (mark.js) as module:

// cs.js
import Mark from './lib/mark.es6.min.js'
window.onload = (event) => {
  console.log(Mark)
}

and when I am visiting any page, there is an error in the console

Uncaught SyntaxError: Cannot use import statement outside a module

The directory structure looks like:

manifest.json
cs.js
lib/mark.es6.min.js

What is the best way in which I can load the mark.js to be able to use in my content script?

Mohammad Faisal
  • 5,783
  • 15
  • 70
  • 117
  • 1
    You can use multiple content scripts. See https://stackoverflow.com/questions/24227874/can-i-share-code-between-different-parts-of-chrome-extension – 1j01 Dec 15 '21 at 06:30
  • 1
    See also [How to import ES6 modules in content script for Chrome Extension](https://stackoverflow.com/q/48104433) – wOxxOm Dec 15 '21 at 09:27

2 Answers2

1

Thanks to 1j01, woxxom and nicola-scionti for good suggestions (Can I share code between different parts of Chrome Extension?, How to import ES6 modules in content script for Chrome Extension and https://stackoverflow.com/a/70359345/725306 respectively).

I ended up using content_scripts only as:

    "content_scripts": [
        {
            "matches": [
                "https://*/*"
            ],
            "js": [
                "lib/mark.es6.min.js",
                "cs.js"
            ]
        }
    ]

and then simply use that in my cs.js

// cs.js
window.onload = (event) => {
  console.log(Mark)
}
Mohammad Faisal
  • 5,783
  • 15
  • 70
  • 117
0

Not exactly what you asked for, but be aware that you can spawn different scripts from the background page:

chrome.tabs.executeScript(tabId, {
  file: "./content_scripts/script1.js",
});

chrome.tabs.executeScript(tabId, {
  file: "./content_scripts/script2.js",
});

And then, the functions you declare in script1.js can be used in script2.js

Nicola Scionti
  • 380
  • 1
  • 12
  • I assume "scripts from the background page" by this you are referring to https://developer.chrome.com/docs/extensions/mv3/service_workers/. right? and the snippet to be placed in script file referred from `background.service_worker` in `manifest.json`. – Mohammad Faisal Dec 15 '21 at 17:28
  • Yes, i'm referring to that script – Nicola Scionti Dec 15 '21 at 18:50