demize
demize

Reputation: 364

JavaScript cannot read property of undefined on variable declared earlier

I get TypeError: Cannot read property 'enabled' of undefined both in the anonymous function (on column 21) and the while loop (on column 15):

var enabled = "unknown";
chrome.runtime.sendMessage({request: "Am I enabled?"}, 
    function(response)
    {
        enabled = response.enabled;
    });

while(enabled == "unknown")
{
    // wait
}

I don't typically write Javascript, so I'm not sure what I could be doing wrong here. Searching gives me results like var y = null; log(y.property); which are not this issue at all.

Upvotes: 0

Views: 215

Answers (1)

Jared Dykstra
Jared Dykstra

Reputation: 3626

The error comes from this line:

 enabled = response.enabled;

because response is undefined.

According to the documentation:

If an error occurs while connecting to the extension, the callback will be called with no arguments and runtime.lastError will be set to the error message.

So, modify your code:

var enabled = "unknown";
chrome.runtime.sendMessage({request: "Am I enabled?"}, 
function(response)
{
    if (!response) {
        // TODO: Check runtime.lastError and take an appropriate action
    } else {
        enabled = response.enabled;
        if (enabled) {
           // TODO: Do the stuff you were planning to do after the while() loop, call a function, etc.
        }
    } 
});

Upvotes: 3

Related Questions