DennisvB
DennisvB

Reputation: 1018

Content Script does not receive the object I send

I am making a chrome extension and I want to send a message from a content script to a background script requesting a var that gets send back. Like this:

contentscript.js --> ask for var --> background.js
                                          |
contentscript.js <-- give var <------------

This are the files:

// contentscript.js

'use strict';

function canGo() {
  chrome.runtime.sendMessage({ message: 'go' }, function(response) {
    return response.go;
  });
}

console.log(canGo()); // undefined

and

// background.js

'use strict';

var go = false;

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    if (request.message == 'go') {
      sendResponse({ go: go });
    }
  }
);

So the problem is that the function canGo returns undefined. I can't find why. Thanks for helping!

Upvotes: 0

Views: 97

Answers (1)

Xan
Xan

Reputation: 77531

chrome.runtime.sendMessage is asynchronous.

Your function canGo() will terminate right after sending the message, and the callback will be called asynchronously later. You cannot use the response immediately, you have to use it from within the callback.

function canGo() {
  chrome.runtime.sendMessage({ message: 'go' }, function(response) {
    console.log(response.go);
    if(response.go) { /* ... */ }
    else { /* ... */ }
  });
}

Upvotes: 1

Related Questions