user244718 user244718 - 12 days ago 6
Javascript Question

Chrome Extension js: Sharing functions between background.js and popup.js

Suppose I have a JavaScript function

foo()
which I want to execute in both the background and in
popup.html
.

For example: it is executed every hour in the background of my Chrome extension, but can also be activated by the user from the popup menu (
popup.html
) on a button click.

I currently have a
global.js
script which defines
foo()
and when I include calls to
foo()
in my
popup.js
document, they execute without issue. (If I include both scripts in
popup.html
)

However, when I try to access
foo()
inside
background.js
, the calls do not execute (even if
global.js
is included in the "background" "manifest.json" extension file:

"background": {
"persistent": true,
"scripts": ["background.js", "global.js"]
},


Is there a convenient way to share functions between
background.js
and
popup.js
(without copying the entire function into each)?

Answer

The background scripts are loaded in the order specified in the manifest file. Simply load the file with common code before your background script as follows:

"background": {
    "persistent": true,
    "scripts": ["global.js", "background.js"]
},

Instead of duplicating the code in the popup, you can also use chrome.extension.getBackgroundPage() from the popup to access functions/variables of the background page, e.g. chrome.extension.getBackgroundPage().myFunction();.