Suppose we have Chrome extension, that uses background page, popup page, maybe some other views and content scripts. There is some constant data relating to the subject area, that has to be accessible from all views and content scripts.
What is the best practice to share this data?
Asked
Active
Viewed 1,924 times
3
2 Answers
9
One approach is to keep all of the shared data in the background page, and access it via getBackgroundPage which is available from most contexts. If unavailable (eg. in a context script), you can use message passing to get at the data.

Boris Smus
- 8,220
- 2
- 36
- 33
-
So your suggest is to define in background page `window.PI = 3.14`. Then in extension views use `chrome.extension.getBackgroundPage().PI` and in content scripts use something like `chrome.extension.sendRequest('giveMePI', function(PI) { /* here we have PI */ })` and again in background page: `chrome.extension.onRequest.addListener(function(req, sender, sendResponse) { if (req == 'giveMePI') { sendResponse(window.PI); } });` Doesn't it seem too complicated for `PI`? – disfated Nov 11 '11 at 19:28
-
5For that kind of stuff, you could make a constants.js file that you inject as a content script AND include from the background page. – Boris Smus Nov 14 '11 at 17:55
-
If you add this comment as a separate answer i will accept it. Thanks – disfated Nov 27 '11 at 13:32
4
As @BorisSmus mentioned, you can create a separate constants.js
file that you include everywhere you need it.
For example, in your manifest.json
:
"content_scripts": [
{
"js": ["constants.js", /* ... your other content scripts ... */]
}
],
And the following at the top of <head>
on your popup and background pages:
<script src="constants.js"></script>
This also has the benefit of not resulting in issues if one of the users of constants.js
accidentally modifies a variable from it, since each user has their own copy.

rvighne
- 20,755
- 11
- 51
- 73