问题
I am new to both JavaScript and Chrome development, and am trying to create an extension that injects content/CSS in certain web pages. Simple enough, but the catch is that to do so it requires looking through a significant amount of data in local storage. From what I've read so far, the correct way to do this would be either:
- Reading the required data (JSON serialized) from storage directly from the content script every time the page is visited, or
- Maintaining the state in the extension background page and transferring the required data (also JSON serialized) to the content script environment using message passing.
Either of these approaches, however, would be extremely inefficient due to large amounts of data being needlessly serialized and deserialized on every page load.
So, I want to know:
Is it in any way possible to maintain a shared memory cache in Chrome that content scripts injected in all tabs can access?
If not, is an alternate approach possible where the background page listens for the
chrome.tabs.onUpdated
event and somehow modifies the target DOM itself?
回答1:
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 tab's DOM.
回答2:
1- Reading the required data (JSON serialized) from storage directly from the content script every time the page is visited.
But you have to do that every time your page is loaded which you want to avoid (I guess)
2- Maintaining the state in the extension background page and transferring the required data (also JSON serialized) to the content script environment using message passing.
The only way to make Content Scripts and Background scripts interact is via Message Passing
. You are not actually looking to an alternative solution but you want to improve the process and avoid message passing each time a page is loaded.
For this, you can develop a spec. The spec states for which URLs or which Domains or based on some condition you want to get the data from Background. If your current URL/Tab agrees with spec only then pass a message to background.
Optionally, Background can also do the same and send message only if your spec is followed. Moreover, when your extension is loaded, you can also cache the storage into local variable.
Use Chrome Storage API to listen for changes in storage and update your local data copy accordingly.
You can also look at this code written by me using the same approach.
来源:https://stackoverflow.com/questions/25453243/share-in-memory-objects-in-chrome-extension-content-scripts