我无法从后台脚本中获取内容脚本请求值。
content_script.js
=================
var elements = undefined
var properties = undefined
var targets = undefined
chrome.extension.sendRequest({greeting: "elements"}, function(response) {
elements = response.input;
});
if (elements == undefined){
var elements = ["a","img"];
}else{
elements = elements.split(',');
}
chrome.extension.sendRequest({greeting: "properties"}, function(response) {
properties = response.input;
});
if (properties == undefined){
var properties = ["alt","id","class"];
}else{
properties = properties.split(',');
}
chrome.extension.sendRequest({greeting: "targets"}, function(response) {
targets = response.input;
});
if (targets == undefined){
var targets = ["onclick","href"];
}else{
targets = targets.split(',');
}...
...More code and references to elements following...
上述代码仅在代码中断(即等待)之前有效,然后再执行与上述值相关的任何操作,我想我可以做一些事情但我宁愿使用更高效的解决方案可能的。
(供参考:)
background.js
=============
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
switch (request.greeting){
case "elements":
var elements = localStorage["elements"];
sendResponse({input: elements});
break;
case "properties":
var properties = localStorage["properties"];
sendResponse({input: properties});
break;
case "targets":
var targets = localStorage["targets"];
sendResponse({input: targets});
break;
}
});
我已经在这里工作了3个小时(仍在学习我正在用JS做什么)
答案 0 :(得分:0)
嗯,你不能这样做:
chrome.extension.sendRequest({greeting: "properties"}, function(response) {
properties = response.input;
});
if (properties == undefined){ // always undefined
var properties = ["alt","id","class"];
}else{
properties = properties.split(',');
}
sendRequest
是异步的。
检查undefined的正确方法是:
if (typeof properties == "undefined")
如果您需要所有这些内容,只需提出1个请求并在回调中执行所有操作:
chrome.extension.sendRequest({greeting: "all"}, function(response) {
if (response.elements === null) {
var elements = ["a","img"];
} else {
var elements = response.elements.split(',');
}
if (response.properties === null) {
var properties = ["alt","id","class"];
} else {
var properties = response.properties.split(',');
}
if (response.targets === null) {
var targets = ["onclick","href"];
} else {
var targets = response.targets.split(',');
}
});
在后台:
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
switch (request.greeting){
case "all":
sendResponse({
elements: localStorage.getItem("targets"),
properties: localStorage.getItem("properties"),
targets: localStorage.getItem("targets")
});
break;
}
});