Calling Api Keys In Background And Content Scripts In Webextension
Solution 1:
This works the way you desire. A single JavaScript file can be used in both background scripts and content scripts to share identical functions or variables.
All the scripts defined in the background
key run in the same context. Thus, your variables APP_KEY
and APP_SEC
, as defined in key.js
, are available to your code in background.js
.
All the scripts defined in a single js
key within a manifest.json file's content_scripts
key share a single context. This is what allows you to use things like jQuery with your code. I have not checked to see if there is a separate context created for separate js
lists, if the matches
key results in both sets being loaded on a particular page, or tab. In addition, I have not checked to see if a single context is shared between the manifest.json file's content_scripts
method of loading content scripts and other methods of loading content scripts (e.g. tabs.executeScript()
).
The following is a complete extension that has been tested in both Firefox and Google Chrome. In both browsers, the variables defined in key.js
are available in both the background and content scripts.
manifest.json:
{"manifest_version":2,"name":"Variables in other files","description":"Test availability of variables from anther JavaScript file","version":"0.1","background":{"scripts":["js/key.js","js/background.js"]},"content_scripts":[{"matches":["*://*.mozilla.org/*"],"js":["js/key.js","js/contentScript.js"]}]}
js/key.js:
varAPP_KEY = 'App Key Goes Here';
varAPP_SEC = 'App Secret Goes Here';
js/background.js:
console.log('Background: ' + APP_KEY);
console.log('Background: ' + APP_SEC);
js/contentScript.js:
console.log('Content: ' + APP_KEY);
console.log('Content: ' + APP_SEC);
Console output upon loading extension:
Background: App Key Goes Here
Background: App Secret Goes Here
Console output upon navigating to mozilla.org
:
Content: App Key Goes Here
Content: App Secret Goes Here
I am not sure why this did not work for you when you initially tried it. You have stated in a comment that it is working for you now.
Post a Comment for "Calling Api Keys In Background And Content Scripts In Webextension"