Mauro
Mauro

Reputation: 142

Does a callback exist for "chrome.storage.local.set"

I need to send back a Chrome message only after the chrome.storage.local has been set, but I cannot find a way to "import" the sendResponse function inside it.

Please consider that all this code is being executed into a background script and triggered by a message sent from a content_script and/or from the browser action popup. So this is why I need to send the response back.

Do you have any idea? 🤣


// Global array
let documents = [];

// Recursive ajax call
function get_and_merge_data(cursor = null, token, sendResponse) {
    //console.log("Data collection started");
    let url = (cursor) ? `https://[omissis]?[omissis]cursor=?{cursor}` : `[omissis]?paging_mode=standard_cursor`;
    //console.log("Cursor: " + cursor);

    $.ajax({
        headers: {
            "X-AUTH-TOKEN": token
        },
        type: "get",
        dataType: "json",
        crossDomain: true,
        url: url,
        // dataType: "json",
        success: function (response, textStatus, xhr) {
            // Silence is golden...
        }
    }).done(function (response) {

        chrome.storage.local.set({ "documents_cache": response }, function (sendResponse) {
            console.log(`documents_cache has been saved`);
            documents = new Array(); // Empty the array

            sendResponse("documents have been loaded and saved!"); // <-- this does not work
        });
        //return
    });
}

Upvotes: 0

Views: 131

Answers (1)

Wex
Wex

Reputation: 15715

The callback signature for chrome.storage.local.set is:

function() {...};

Yet you're passing it:

        function (sendResponse) {
            console.log(`documents_cache has been saved`);
            documents = new Array(); // Empty the array

            sendResponse("documents have been loaded and saved!"); // <-- this does not work
        }

The sendResponse variable defined in the above callback is going to be undefined, and it will overwrite the original sendResponse which was originally declared here:

// Recursive ajax call
function get_and_merge_data(cursor = null, token, sendResponse) {

All this to say, simply change your callback to .set to take no arguments:

        function () {
            console.log(`documents_cache has been saved`);
            documents = new Array(); // Empty the array

            sendResponse("documents have been loaded and saved!"); // <-- this does not work
        }

Upvotes: 2

Related Questions