Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome extension store

when building my Google Chrome extension, I run into a problem with storing it's settings. I have created a settings page which is opened in a tab after the user clicks browserAction icon. This pages has UI for setting up my extension and it can, for example, store the settings into localStore. But the background page of my extension, which is supposed to read these settings, doesn't have any localStore.

Where should I store the extension settings so it would be accessible from anywhere in the browser and stored "forever"?

Thanks for any help...

like image 262
Kaspi Avatar asked May 22 '26 01:05

Kaspi


1 Answers

If you want to store data temporarly by using your backgroundpage:

// in your backgroundpage
// Set a value
window['yourvalue']=123;
// Get a value
alert(window['yourvalue']);

// in any other page (options/popup/message/whatever)
var bg=chrome.extension.getBackgroundPage();
// Set a value
bg['yourvalue']=123;
// Get a value
alert(bg['yourvalue']);

I always use these functions in my extensions:

var bg=chrome.extension.getBackgroundPage();
// Save data
function save(key, val) {
    bg[key]=val;
    var data={};
    var tmp=localStorage.getItem("MyPlugin");

    if(tmp!=null&&tmp.indexOf("{")>-1&&tmp.indexOf("}")>-1)
    {
        data=JSON.parse(tmp);
    }
    data[key]=val;
    localStorage.setItem("MyPlugin", JSON.stringify(data));
}

// Restore the data
var data={};
var tmp=localStorage.getItem("MyPlugin");

if(tmp!=null&&tmp.indexOf("{")>-1&&tmp.indexOf("}")>-1)
{
    data=JSON.parse(tmp);
    for (var key in data) {
        if (data.hasOwnProperty(key)) {
            bg[key]=data[key];
        }
    }
}
like image 169
Oliver Avatar answered May 23 '26 13:05

Oliver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!