2

I have a function that is checking for a stored value through chrome.storage.sync.get and inserting a CSS file upon existence of said stored value.

I realize chrome.storage.sync.get is an async function and the return value is not passing back as expected to the makeAggressive() function. However, I don't know how else to write this code to get the result of if (result == 'aggressive') passed to makeAggressive().

How can I retrieve the stored value, check its value and return the result to the calling function?

chrome.tabs.onUpdated.addListener(function(tabId, info, tab) {
    if (info.status == 'complete') applyCSS(tab);
});

function applyCSS(tab) {
    var tabUrl = tab.url;

    if (makeAggressive()) {
        chrome.tabs.insertCSS(tab.id, {
            file: "aggressive.css"
        });
    }
}

function makeAggressive() {
    chrome.storage.sync.get(function(items) {
        var result = items.intensityLevel;
        if (result == 'aggressive') {
            return true;
        }
  });
}
1

1 Answer 1

2

Simply pass a callback into the async function.
The callback shall be called once the asynchronous activity is completed.

async_function(function() {
    // do something after async_function completes and invokes this callback
});

function async_function(callback) {
    something_async(function(result) {
        callback(result);
    });
}

In your case:

function applyCSS(tab) {
    var tabUrl = tab.url;

    makeAggressive(function() {
        chrome.tabs.insertCSS(tab.id, {
            file: "aggressive.css"
        });
    });
}

function makeAggressive(callback) {
    chrome.storage.sync.get(function(items) {
        var result = items.intensityLevel;
        if (result == 'aggressive') {
            callback();
        }
    });
}
Sign up to request clarification or add additional context in comments.

2 Comments

This worked although I need to get my head around callbacks to understand WHY this worked!
Read the linked duplicate question's answer or find some other tutorial.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.