Maxim
Maxim

Reputation: 619

Google Chrome extension - importing function into content script

I'm struggling to split my content script for a Google Chrome addon into different files. If I put two scripts in the manifest.json, the second script doesnt have access to any function definitions from the first script. I tried assigning the function to the window context, but that didnt work either.

   "js": [
    "content-scripts/script1.js",
    "content-scripts/script2.js"
  ]

...

//script1.json
function myFunction(){...}
window.myFunction = myFunction

//script2.json
console.log(myFunction)  //undefined
console.log(window.myFunction) //undefined

I have tried for quite some time now, it's a little surprising that a simple task like this doesn't work. Can anyone help?

Upvotes: 1

Views: 19

Answers (1)

Shweta Matkar
Shweta Matkar

Reputation: 311

This happens because each content script in a Chrome extension runs in an isolated execution environment (a separate JavaScript scope). This means that variables and functions defined in one content script are not directly accessible in another, even if both are listed in manifest.json.

Instead of relying on the window object, extract shared functions into a separate module and import it in both content scripts.

  • Create a shared module (e.g., shared.js):

// content-scripts/shared.js
export function myFunction() {
    console.log("Hello from shared function");
}

  • Import the module in both scripts:

// content-scripts/script1.js
import { myFunction } from "./shared.js";
myFunction();

// content-scripts/script2.js
import { myFunction } from "./shared.js";
myFunction();

Note: Importing like this requires the type: "module" property in manifest.json (only supported in Manifest V3).

Upvotes: 0

Related Questions