Besides using localStorage (via the man page), you can directly save these variables on the background page by exchanging messages from the contents of the script to the background image. If these variables are located on the extension page (other content or scripts entered), you can easily save them using the chrome.extension.getBackgroundPage().window.variableYouWant and access these variables in the contents of the script by messaging.
If these variables are in the contents of the script, use messaging to send these variables to the following page:
chrome.runtime.sendMessage(object);
object can be any object you want to send.
on the background page there is such a lysner:
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) { myVariabeInBackground = message.yourObjectProperties; });
when you need these variables, you can use chrome.extension.getBackgroundPage().window.myVariabeInBackground on your extension page (except for the contents of the script) or you can send a message from the background page to the content of the script by calling chrome.tabs.sendMessage(tabId, messageObject) on the background page itself and get in the contents of the script, having this list:
chrome.runtime.onMessage.addListener( function(request, sender) {});
For localStorage, you can also do the same to get this saved variable in your script content.
And no, you cannot directly access the background page from the contents of the script.
PS: variables on the original page will reset if the extension is reloaded. If you want to use these variables, even after restarting the extension, use local storage. The extension does not restart in browser actions.
Read more at https://developer.chrome.com/extensions/messaging
source share