开发者

Help with chrome extension message passing

I am trying to get a string of values from a background page to my content script in a Google Chrome 开发者_C百科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


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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜