Chrome extension: How can I extract variable-value pairs from imported .json file with javascript?

532 views Asked by At

I'm writing a chrome extension, and I'm exporting and importing a json file from the options page.

function export_theme() {
    chrome.storage.sync.get({
        'colorBg': '',
        'colorFg': '',
        'colorHi': '',
        'colorBtn': '',
        'colorDrop': '',
        'colorLi': '',
        'colorLi2': ''
    },
    function(items){
        var result = JSON.stringify(items);
        var url = 'data:application/json;base64,' + btoa(result);
        var name = 'custom_theme';
        chrome.downloads.download({
            url: url,
            saveAs: true
        });
    });
};

This stores correctly as file. Example:

{"colorBg":"#ffffff","colorBtn":"#000000","colorDrop":"#666666","colorFg":"#333333","colorHi":"#cc0000","colorLi":"#000000","colorLi2":"#000000"}

But I couldn't find a chrome api to import the .json file back in. I have searched on stackoverflow and found this -- https://stackoverflow.com/a/38838572/8116516, and it's working.

function import_theme(e) {
    var files = e.target.files, reader = new FileReader();
    reader.onload = _imp;
    reader.readAsText(files[0]);
}

function _imp() {
    var colors = JSON.parse(this.result);
    console.log(colors);
    document.getElementById('import').value = ''; 
}

The import is successful, I can view the list in the console, but I have no idea how to get the values back into my chrome storage from this json object. Is there a chrome api for this? How can I extract the variables and hex color values to set them in the existing chrome storage?

If I should provide any more info or code, please tell me. The project is pretty large and I was unsure what could be helpful. I'm relatively new to all of this.

0

There are 0 answers