Shan
Shan

Reputation: 2832

How to use another javascript file in Chrome extension

How to use the functions of a javascript file in contentscript.js? I have some functions in a1.js and I want to know how to call those in contentscript.js

a1.js is also part of extension and is in the same folder as contentscript.js

Upvotes: 2

Views: 2930

Answers (1)

Rob W
Rob W

Reputation: 348972

Put them in your manifest.json file:

  ....
  "content_scripts": [
    {
      "matches": ["*://*/*"],
      "js": ["a1.js", "contentscript.js"]
    }
  ],
  ....

a1.js will be loaded first, then contentscript.js.

Example:

// a1.js
function x() { return 100; }
alert(typeof y); // undefined, because `contentscript.js` is not loaded yet
setTimeout( function(){alert(typeof y;)}, 1000 ); // function

// contentscript.js
function y() {
    alert(x()); // Shows 100
}

Upvotes: 4

Related Questions