Share objects in memory in Chrome extension content scripts?

I am new to JavaScript and Chrome development and am trying to create an extension that injects content / CSS on specific web pages. Simple enough, but it means that it requires viewing a significant amount of data in local storage. From what I've read so far, the correct way to do this would be:

  • Reading the required data (JSON serialization) from storage directly from the script content on every page visit, or
  • Storing the state in the extension's sub page and passing the required data (also serialized JSON) to the script content environment using message passing.
However, any of these approaches would be extremely inefficient due to the large amount of data that was unnecessarily serialized and deserialized on every page load.

So, I want to know:

  • Is it not possible to keep a shared memory cache in Chrome that can be accessed by content scripts entered in all tabs?

  • If not, is there an alternative approach possible where the background page listens for an event chrome.tabs.onUpdated

    and modifies the DOM object itself in some way?

+3


source to share


2 answers


1) I don't think this is possible. You seem to have exhausted the possibilities.



2) Content scripts are the only way to access / modify a normal DOM tab.

0


source


1- Reading required data (JSON serialized) from storage directly from script content on every page visit.

But you have to do this every time your page is loaded which you want to avoid (I think)

2. Saving the state in the rich background page and passing the required data (also serialized JSON) to the content script environment using message passing.

The only way content and background scripting scripts interact is Message Passing

. You're not really looking for an alternative solution, but you want to improve the process and avoid passing messages every time the page loads.



You can develop a specification for this. Spec indicates for which URLs or which domains or based on some condition you want to get data from Background. If your current URL / contribution agrees with the spec, then pipe the message to the background.

Optionally, Background can also do the same and send a message only if your spec is met. Additionally, when your extension is loaded, you can also cache the storage to a local variable.

Use the Storage Storage API to listen for changes in the storage and update the local copy of the data accordingly.

You can also look at this code I wrote using the same approach.

0


source







All Articles