Glebcha
Glebcha

Reputation: 171

How can I sync to extension local storage in content script?

Now I use chrome.extension.sendMessage in content script and chrome.extension.onMessage.addListener in background script. But the problem appears when I need to sync to extension's local storage in real time (several checkboxes with options in extension popup).

Popup with checkbox (to control content-script.js options) -> checkbox state stored in extension's local storage.

Content script need to know changes made by user in popup window -> send request to Background page to access extension's local storage keys.

Background page -> send response to Content script -> callback function replicate all keys from extension's local storage to web local storage.

Content script read replicated keys and turn on/off it's options.

But this process is not real-time and I need it to be reactive.

Content-script.js:

chrome.extension.sendMessage({
    name: "cache"
},
function(response) {
    var status = response.url;
    if (status == 'enabled') {
        localStorage['cache'] = 'enabled';
    }
    if (status == 'disabled') {
        localStorage['cache'] = 'disabled';
    }
}
);

Backround.js:

chrome.extension.onMessage.addListener(
function(request, sender, sendResponse) {
    console.log("request recieved is " + request);
    if (request.name == "cache") {
        sendResponse({
            url: JSON.parse(localStorage['cache']).status
        });
    } else {}
}
);

Thanks for your help!

Upvotes: 1

Views: 3258

Answers (1)

yoz
yoz

Reputation: 952

Have you looked into the chrome.storage API? One of the specific use cases it's designed for (an advantage over localStorage) is that content scripts can access this API directly, removing the need for messaging to communicate with your background page. (You might even be able to eliminate the background page altogether.)

https://developer.chrome.com/extensions/storage

Upvotes: 7

Related Questions