orschiro
orschiro

Reputation: 21843

chrome.storage.sync does not store the data

I am trying to store the data a user enters inside a textarea in a popup.html. Using jQuery on window unload the data should be synced and on window ready the data should be restored. However, when opening popup.html the content of the textarea is undefined. This is the jQuery code which I am loading in popup.html:

$(window).unload (
    function save() {
        var textarea = document.querySelector("#contacts").value;
        // Old method of storing data locally
        //localStorage["contacts"] = textarea.value;

        // Save data using the Chrome extension storage API.
        chrome.storage.sync.set({contacts: textarea}, function() {
            console.log("Contacts saved");
        });
    });

$(window).ready(
    function restore() {
        var textarea = document.querySelector("#contacts");
        // Old method of retrieving data locally
        // var content = localStorage["contacts"];
        chrome.storage.sync.get('contacts', function(r) {
            console.log("Contacts retrieved");
            var content = r["contacts"];
            textarea.value = content;
        });
    });

Upvotes: 1

Views: 1552

Answers (2)

Ivan Ferrer Villa
Ivan Ferrer Villa

Reputation: 2158

From popup.js you can invoke a method in background.js file to save the data:

popup.js:

addEventListener("unload", function(){
    var background = chrome.extension.getBackgroundPage();
    background.mySavefunction(data);
}

background.js:

function mySaveFunction(data){
    chrome.storage.sync.set(data, function(){
       console.log("Data saved.");
    });
}

Upvotes: 4

orschiro
orschiro

Reputation: 21843

I found a solution. Instead of using $(window).unload() I now use a submit button which needs to be clicked before closing popup.html:

$("#save-button").click(function() {
        var textarea = document.querySelector("#contacts").value;
        var save = {};
        save["contacts"] = textarea;
        // Save data using the Chrome extension storage API.
        chrome.storage.sync.set(save, function() {
            console.log("Contacts saved");
        });
        $("#confirm").text("Contacts saved.").show().fadeOut(5000);
});

Upvotes: 1

Related Questions