帮助Chrome扩展消息传递 [英] Help with chrome extension message passing
问题描述
我试图从一个背景页面中获取一串值到我制作的Google Chrome扩展程序中的内容脚本。
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.
请帮助
推荐答案
大多数(如果不是全部)Chrome扩展API都是异步
。当 sendRequest
被触发时,警报将被触发。在这种情况下,它将是一个空字符串。由于
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.
现在,您可以重新构建代码,以便利用异步事件。例如:
$ b
content_script.js
Now, what you can do is re-architect your code so that you can take advantage of the asynchronous matter. For example:
chrome.extension.sendRequest({action: 'list'}, function(response) {
onListReceived(response.data)
});
function onListReceived(list) {
alert(list);
}
这篇关于帮助Chrome扩展消息传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!