Frage

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?

War es hilfreich?

Lösung

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.

Andere Tipps

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top