Monday, June 3, 2024
24
rated 0 times [  31] [ 7]  / answers: 1 / hits: 8072  / 10 Years ago, sat, march 29, 2014, 12:00:00

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)?


More From » google-chrome-extension

 Answers
3

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();.


[#46445] Friday, March 28, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kenyamelinad

Total Points: 339
Total Questions: 85
Total Answers: 116

Location: Marshall Islands
Member since Sun, Aug 29, 2021
3 Years ago
;