Chrome extension: save tab variables even if page change

I am creating a Chrome extension. I was wondering if there is a way to remember js variables for a tab, even if the page changes. E.g. If I'm on example1.com and go to example2.com on the same tab, I have to save the variables that were set on example1.com. I do not want to use Chrome Storage.

I cannot use localStorage or sessionStorage because chrome has different repositories for different domains. In what ways can this be achieved?

+6
source share
3 answers

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) {}); //request is your sent object. 

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

+4
source

use localstorage. the extension is completely isolated from the page in the function and variable store. you will need to use localstorage on the background page, so when you change the tabs the variable will never be lost.

0
source

You should learn the chrome.storage API as an alternative to localStorage + Messaging.

It is asynchronous compared to localStorage , but it is also Messaging, and Messaging only for the storage variable leads to a large number of templates.

See the documentation here and a recent review (for me) of the pros / cons here.

0
source

Source: https://habr.com/ru/post/971140/


All Articles