ElsaInSpirit
ElsaInSpirit

Reputation: 341

How can I use a function from one Javascript file in another?

I have the following Javascript file, one.js:

function doSomething() {
    console.log("doing stuff");
}

I have another Javascript file, two.js, in which I want to call doSomething():

doSomething();

How can I achieve this? Note this code is for a browser extension so I cannot use html.

Upvotes: 0

Views: 63

Answers (2)

Harun Or Rashid
Harun Or Rashid

Reputation: 5957

You have to import the function from one.js as below :
import doSomething from "one.js";

Then assign it to some variable of current object and use it.
this.doSomething = doSomething();

Upvotes: 2

Muhammad Aadil Banaras
Muhammad Aadil Banaras

Reputation: 1284

you can use scripts as background and content script in extensions code, you can do something like that,

 "background": {
 "scripts": [ "js/sharedFunctions.js", "js/mainBackground.js" ]
 },
"content_scripts": [
  {
    "matches": ["*://*/*"],
    "js": ["js/sharedFunctions.js", "js/mainContentScript.js"]
  }
]

then functions of first file can be used in second as per order

Upvotes: 0

Related Questions