Compartir datos constantes entre vistas en la extensión de Google Chrome

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?

preguntado el 08 de noviembre de 11 a las 14:11

2 Respuestas

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 paso de mensajes para llegar a los datos.

respondido 08 nov., 11:21

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? - deshonrado

For 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

If you add this comment as a separate answer i will accept it. Thanks - deshonrado

As @BorisSmus mentioned, you can create a separate constants.js file that you include everywhere you need it.

Por ejemplo, en tu 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.

Respondido 02 Abr '17, 04:04

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.