views:

31

answers:

1

I am trying to get a string of values from a background page to my content script in a Google Chrome extension I am making.

The problem I am encountering is that when I try to get the value to the content script, it doesn't go. Here is the code

var list1 = "";
chrome.extension.sendRequest({action: 'list'}, function(response) {
      list1 = response.data;
   alert("hey from inside:" + list1 +":"+response.data);
});
alert(list1);

The first alert that comes up shows properly saying "hey from inside" and the list I want the content script to have. But then, when I try to alert the variable that I stored it in from outside of that request, it doesn't show the list.

Please help

+3  A: 

Hi Mike,

Most (if not all) of the Chrome Extensions API are asynchronous. When your sendRequest gets fired, the alert will be fired. In this case it will be an empty string. You cannot guarantee the delivery of list1, because of this asynchronous nature.

Now, what you can do is re-architect your code so that you can take advantage of the asynchronous matter. For example:

content_script.js

chrome.extension.sendRequest({action: 'list'}, function(response) {
   onListReceived(response.data)
});

function onListReceived(list) {
  alert(list);
}
Mohamed Mansour