質問

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?

役に立ちましたか?

解決

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.

他のヒント

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top