0

I'm failing hard in trying to import/export functions from one file to another with a Chrome Extension. My problem is the following:

I have one script that's loaded as a content script from the manifest.js file. That script's name is script.js. In that script, I have a code like this to detect the URL of the webpage I've opened (in order to start my extension):

chrome.runtime.sendMessage({ command: 'currentTab' }, (tab) => { console.log('We're in.') });

Also, in the same script I have a function to attach two other scripts that I will use them as modules since they have export/import functions. These are: core.js and utils.js. The function is:

injectScript('extension.../modules/core.js');
injectScript('extension.../modules/utils.js');

function injectScript(scriptURL) {
    const script = document.createElement('script');
    script.setAttribute('type', 'module');
    script.setAttribute('src', scriptURL);
    const head = document.head || document.getElementsByTagName('head')[0] || document.documentElement;
    head.insertBefore(script, head.lastChild);
}

So, this first script.js sends a message to the background.js script in order to check for the tab URL and if everything's correct, I'll insert as modules my two other scripts.

Now, when I detect the URL of the website as OK, I would like to execute a function start() (which is in core.js) from this main script.js in order to execute everything from core.js that uses imported functions from utils.js.

I've also detected that if I inject my utils.js with the script.js it also injects it through the manifest.json. I'm really stuck in here guys. Could you give me a hand with this spaghetti mess?

Thank you!

Dexter
  • 25
  • 7
  • Your injectScript runs the script as a normal page script, not as a content script, so it can't use sendMessage. Why do you use normal page scripts? – wOxxOm Oct 14 '21 at 17:36
  • Because I am trying to attach those scripts as modules so I can use imports/exports. Isn't that the right way to do it? I am reading a response you gave me in a previous post and it says something about using 'chrome.tabs.executeScript'. Could you guide me a little better? – Dexter Oct 14 '21 at 17:39
  • Use import(), [example](https://stackoverflow.com/a/53033388). – wOxxOm Oct 14 '21 at 17:41
  • Working great. Thank you! – Dexter Oct 14 '21 at 18:15

0 Answers0