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